PackageManagerService.java revision dd963c63657363871d768a38789bec41878ffb09
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.signingDetailsHasCertificate;
112import static com.android.server.pm.PackageManagerServiceUtils.signingDetailsHasSha256Certificate;
113import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures;
114import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE;
115import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS;
116import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
117
118import android.Manifest;
119import android.annotation.IntDef;
120import android.annotation.NonNull;
121import android.annotation.Nullable;
122import android.app.ActivityManager;
123import android.app.ActivityManagerInternal;
124import android.app.AppOpsManager;
125import android.app.IActivityManager;
126import android.app.ResourcesManager;
127import android.app.admin.IDevicePolicyManager;
128import android.app.admin.SecurityLog;
129import android.app.backup.IBackupManager;
130import android.content.BroadcastReceiver;
131import android.content.ComponentName;
132import android.content.ContentResolver;
133import android.content.Context;
134import android.content.IIntentReceiver;
135import android.content.Intent;
136import android.content.IntentFilter;
137import android.content.IntentSender;
138import android.content.IntentSender.SendIntentException;
139import android.content.ServiceConnection;
140import android.content.pm.ActivityInfo;
141import android.content.pm.ApplicationInfo;
142import android.content.pm.AppsQueryHelper;
143import android.content.pm.AuxiliaryResolveInfo;
144import android.content.pm.ChangedPackages;
145import android.content.pm.ComponentInfo;
146import android.content.pm.FallbackCategoryProvider;
147import android.content.pm.FeatureInfo;
148import android.content.pm.IDexModuleRegisterCallback;
149import android.content.pm.IOnPermissionsChangeListener;
150import android.content.pm.IPackageDataObserver;
151import android.content.pm.IPackageDeleteObserver;
152import android.content.pm.IPackageDeleteObserver2;
153import android.content.pm.IPackageInstallObserver2;
154import android.content.pm.IPackageInstaller;
155import android.content.pm.IPackageManager;
156import android.content.pm.IPackageManagerNative;
157import android.content.pm.IPackageMoveObserver;
158import android.content.pm.IPackageStatsObserver;
159import android.content.pm.InstantAppInfo;
160import android.content.pm.InstantAppRequest;
161import android.content.pm.InstantAppResolveInfo;
162import android.content.pm.InstrumentationInfo;
163import android.content.pm.IntentFilterVerificationInfo;
164import android.content.pm.KeySet;
165import android.content.pm.PackageCleanItem;
166import android.content.pm.PackageInfo;
167import android.content.pm.PackageInfoLite;
168import android.content.pm.PackageInstaller;
169import android.content.pm.PackageList;
170import android.content.pm.PackageManager;
171import android.content.pm.PackageManagerInternal;
172import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
173import android.content.pm.PackageManagerInternal.PackageListObserver;
174import android.content.pm.PackageParser;
175import android.content.pm.PackageParser.ActivityIntentInfo;
176import android.content.pm.PackageParser.Package;
177import android.content.pm.PackageParser.PackageLite;
178import android.content.pm.PackageParser.PackageParserException;
179import android.content.pm.PackageParser.ParseFlags;
180import android.content.pm.PackageParser.ServiceIntentInfo;
181import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion;
182import android.content.pm.PackageStats;
183import android.content.pm.PackageUserState;
184import android.content.pm.ParceledListSlice;
185import android.content.pm.PermissionGroupInfo;
186import android.content.pm.PermissionInfo;
187import android.content.pm.ProviderInfo;
188import android.content.pm.ResolveInfo;
189import android.content.pm.ServiceInfo;
190import android.content.pm.SharedLibraryInfo;
191import android.content.pm.Signature;
192import android.content.pm.UserInfo;
193import android.content.pm.VerifierDeviceIdentity;
194import android.content.pm.VerifierInfo;
195import android.content.pm.VersionedPackage;
196import android.content.pm.dex.ArtManager;
197import android.content.pm.dex.DexMetadataHelper;
198import android.content.pm.dex.IArtManager;
199import android.content.res.Resources;
200import android.database.ContentObserver;
201import android.graphics.Bitmap;
202import android.hardware.display.DisplayManager;
203import android.net.Uri;
204import android.os.Binder;
205import android.os.Build;
206import android.os.Bundle;
207import android.os.Debug;
208import android.os.Environment;
209import android.os.Environment.UserEnvironment;
210import android.os.FileUtils;
211import android.os.Handler;
212import android.os.IBinder;
213import android.os.Looper;
214import android.os.Message;
215import android.os.Parcel;
216import android.os.ParcelFileDescriptor;
217import android.os.PatternMatcher;
218import android.os.Process;
219import android.os.RemoteCallbackList;
220import android.os.RemoteException;
221import android.os.ResultReceiver;
222import android.os.SELinux;
223import android.os.ServiceManager;
224import android.os.ShellCallback;
225import android.os.SystemClock;
226import android.os.SystemProperties;
227import android.os.Trace;
228import android.os.UserHandle;
229import android.os.UserManager;
230import android.os.UserManagerInternal;
231import android.os.storage.IStorageManager;
232import android.os.storage.StorageEventListener;
233import android.os.storage.StorageManager;
234import android.os.storage.StorageManagerInternal;
235import android.os.storage.VolumeInfo;
236import android.os.storage.VolumeRecord;
237import android.provider.Settings.Global;
238import android.provider.Settings.Secure;
239import android.security.KeyStore;
240import android.security.SystemKeyStore;
241import android.service.pm.PackageServiceDumpProto;
242import android.system.ErrnoException;
243import android.system.Os;
244import android.text.TextUtils;
245import android.text.format.DateUtils;
246import android.util.ArrayMap;
247import android.util.ArraySet;
248import android.util.Base64;
249import android.util.DisplayMetrics;
250import android.util.EventLog;
251import android.util.ExceptionUtils;
252import android.util.Log;
253import android.util.LogPrinter;
254import android.util.LongSparseArray;
255import android.util.LongSparseLongArray;
256import android.util.MathUtils;
257import android.util.PackageUtils;
258import android.util.Pair;
259import android.util.PrintStreamPrinter;
260import android.util.Slog;
261import android.util.SparseArray;
262import android.util.SparseBooleanArray;
263import android.util.SparseIntArray;
264import android.util.TimingsTraceLog;
265import android.util.Xml;
266import android.util.jar.StrictJarFile;
267import android.util.proto.ProtoOutputStream;
268import android.view.Display;
269
270import com.android.internal.R;
271import com.android.internal.annotations.GuardedBy;
272import com.android.internal.app.IMediaContainerService;
273import com.android.internal.app.ResolverActivity;
274import com.android.internal.content.NativeLibraryHelper;
275import com.android.internal.content.PackageHelper;
276import com.android.internal.logging.MetricsLogger;
277import com.android.internal.os.IParcelFileDescriptorFactory;
278import com.android.internal.os.SomeArgs;
279import com.android.internal.os.Zygote;
280import com.android.internal.telephony.CarrierAppUtils;
281import com.android.internal.util.ArrayUtils;
282import com.android.internal.util.ConcurrentUtils;
283import com.android.internal.util.DumpUtils;
284import com.android.internal.util.FastXmlSerializer;
285import com.android.internal.util.IndentingPrintWriter;
286import com.android.internal.util.Preconditions;
287import com.android.internal.util.XmlUtils;
288import com.android.server.AttributeCache;
289import com.android.server.DeviceIdleController;
290import com.android.server.EventLogTags;
291import com.android.server.FgThread;
292import com.android.server.IntentResolver;
293import com.android.server.LocalServices;
294import com.android.server.LockGuard;
295import com.android.server.ServiceThread;
296import com.android.server.SystemConfig;
297import com.android.server.SystemServerInitThreadPool;
298import com.android.server.Watchdog;
299import com.android.server.net.NetworkPolicyManagerInternal;
300import com.android.server.pm.Installer.InstallerException;
301import com.android.server.pm.Settings.DatabaseVersion;
302import com.android.server.pm.Settings.VersionInfo;
303import com.android.server.pm.dex.ArtManagerService;
304import com.android.server.pm.dex.DexLogger;
305import com.android.server.pm.dex.DexManager;
306import com.android.server.pm.dex.DexoptOptions;
307import com.android.server.pm.dex.PackageDexUsage;
308import com.android.server.pm.permission.BasePermission;
309import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
310import com.android.server.pm.permission.PermissionManagerService;
311import com.android.server.pm.permission.PermissionManagerInternal;
312import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
313import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
314import com.android.server.pm.permission.PermissionsState;
315import com.android.server.pm.permission.PermissionsState.PermissionState;
316import com.android.server.security.VerityUtils;
317import com.android.server.storage.DeviceStorageMonitorInternal;
318
319import dalvik.system.CloseGuard;
320import dalvik.system.VMRuntime;
321
322import libcore.io.IoUtils;
323
324import org.xmlpull.v1.XmlPullParser;
325import org.xmlpull.v1.XmlPullParserException;
326import org.xmlpull.v1.XmlSerializer;
327
328import java.io.BufferedOutputStream;
329import java.io.ByteArrayInputStream;
330import java.io.ByteArrayOutputStream;
331import java.io.File;
332import java.io.FileDescriptor;
333import java.io.FileInputStream;
334import java.io.FileOutputStream;
335import java.io.FilenameFilter;
336import java.io.IOException;
337import java.io.PrintWriter;
338import java.lang.annotation.Retention;
339import java.lang.annotation.RetentionPolicy;
340import java.nio.charset.StandardCharsets;
341import java.security.DigestException;
342import java.security.DigestInputStream;
343import java.security.MessageDigest;
344import java.security.NoSuchAlgorithmException;
345import java.security.PublicKey;
346import java.security.SecureRandom;
347import java.security.cert.CertificateException;
348import java.util.ArrayList;
349import java.util.Arrays;
350import java.util.Collection;
351import java.util.Collections;
352import java.util.Comparator;
353import java.util.HashMap;
354import java.util.HashSet;
355import java.util.Iterator;
356import java.util.LinkedHashSet;
357import java.util.List;
358import java.util.Map;
359import java.util.Objects;
360import java.util.Set;
361import java.util.concurrent.CountDownLatch;
362import java.util.concurrent.Future;
363import java.util.concurrent.TimeUnit;
364import java.util.concurrent.atomic.AtomicBoolean;
365import java.util.concurrent.atomic.AtomicInteger;
366
367/**
368 * Keep track of all those APKs everywhere.
369 * <p>
370 * Internally there are two important locks:
371 * <ul>
372 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
373 * and other related state. It is a fine-grained lock that should only be held
374 * momentarily, as it's one of the most contended locks in the system.
375 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
376 * operations typically involve heavy lifting of application data on disk. Since
377 * {@code installd} is single-threaded, and it's operations can often be slow,
378 * this lock should never be acquired while already holding {@link #mPackages}.
379 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
380 * holding {@link #mInstallLock}.
381 * </ul>
382 * Many internal methods rely on the caller to hold the appropriate locks, and
383 * this contract is expressed through method name suffixes:
384 * <ul>
385 * <li>fooLI(): the caller must hold {@link #mInstallLock}
386 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
387 * being modified must be frozen
388 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
389 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
390 * </ul>
391 * <p>
392 * Because this class is very central to the platform's security; please run all
393 * CTS and unit tests whenever making modifications:
394 *
395 * <pre>
396 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
397 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
398 * </pre>
399 */
400public class PackageManagerService extends IPackageManager.Stub
401        implements PackageSender {
402    static final String TAG = "PackageManager";
403    public static final boolean DEBUG_SETTINGS = false;
404    static final boolean DEBUG_PREFERRED = false;
405    static final boolean DEBUG_UPGRADE = false;
406    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
407    private static final boolean DEBUG_BACKUP = false;
408    public static final boolean DEBUG_INSTALL = false;
409    public static final boolean DEBUG_REMOVE = false;
410    private static final boolean DEBUG_BROADCASTS = false;
411    private static final boolean DEBUG_SHOW_INFO = false;
412    private static final boolean DEBUG_PACKAGE_INFO = false;
413    private static final boolean DEBUG_INTENT_MATCHING = false;
414    public static final boolean DEBUG_PACKAGE_SCANNING = false;
415    private static final boolean DEBUG_VERIFY = false;
416    private static final boolean DEBUG_FILTERS = false;
417    public static final boolean DEBUG_PERMISSIONS = false;
418    private static final boolean DEBUG_SHARED_LIBRARIES = false;
419    public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
420
421    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
422    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
423    // user, but by default initialize to this.
424    public static final boolean DEBUG_DEXOPT = false;
425
426    private static final boolean DEBUG_ABI_SELECTION = false;
427    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
428    private static final boolean DEBUG_TRIAGED_MISSING = false;
429    private static final boolean DEBUG_APP_DATA = false;
430
431    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
432    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
433
434    private static final boolean HIDE_EPHEMERAL_APIS = false;
435
436    private static final boolean ENABLE_FREE_CACHE_V2 =
437            SystemProperties.getBoolean("fw.free_cache_v2", true);
438
439    private static final int RADIO_UID = Process.PHONE_UID;
440    private static final int LOG_UID = Process.LOG_UID;
441    private static final int NFC_UID = Process.NFC_UID;
442    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
443    private static final int SHELL_UID = Process.SHELL_UID;
444    private static final int SE_UID = Process.SE_UID;
445
446    // Suffix used during package installation when copying/moving
447    // package apks to install directory.
448    private static final String INSTALL_PACKAGE_SUFFIX = "-";
449
450    static final int SCAN_NO_DEX = 1<<0;
451    static final int SCAN_UPDATE_SIGNATURE = 1<<1;
452    static final int SCAN_NEW_INSTALL = 1<<2;
453    static final int SCAN_UPDATE_TIME = 1<<3;
454    static final int SCAN_BOOTING = 1<<4;
455    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6;
456    static final int SCAN_REQUIRE_KNOWN = 1<<7;
457    static final int SCAN_MOVE = 1<<8;
458    static final int SCAN_INITIAL = 1<<9;
459    static final int SCAN_CHECK_ONLY = 1<<10;
460    static final int SCAN_DONT_KILL_APP = 1<<11;
461    static final int SCAN_IGNORE_FROZEN = 1<<12;
462    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13;
463    static final int SCAN_AS_INSTANT_APP = 1<<14;
464    static final int SCAN_AS_FULL_APP = 1<<15;
465    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16;
466    static final int SCAN_AS_SYSTEM = 1<<17;
467    static final int SCAN_AS_PRIVILEGED = 1<<18;
468    static final int SCAN_AS_OEM = 1<<19;
469    static final int SCAN_AS_VENDOR = 1<<20;
470    static final int SCAN_AS_PRODUCT = 1<<21;
471
472    @IntDef(flag = true, prefix = { "SCAN_" }, value = {
473            SCAN_NO_DEX,
474            SCAN_UPDATE_SIGNATURE,
475            SCAN_NEW_INSTALL,
476            SCAN_UPDATE_TIME,
477            SCAN_BOOTING,
478            SCAN_DELETE_DATA_ON_FAILURES,
479            SCAN_REQUIRE_KNOWN,
480            SCAN_MOVE,
481            SCAN_INITIAL,
482            SCAN_CHECK_ONLY,
483            SCAN_DONT_KILL_APP,
484            SCAN_IGNORE_FROZEN,
485            SCAN_FIRST_BOOT_OR_UPGRADE,
486            SCAN_AS_INSTANT_APP,
487            SCAN_AS_FULL_APP,
488            SCAN_AS_VIRTUAL_PRELOAD,
489    })
490    @Retention(RetentionPolicy.SOURCE)
491    public @interface ScanFlags {}
492
493    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
494    /** Extension of the compressed packages */
495    public final static String COMPRESSED_EXTENSION = ".gz";
496    /** Suffix of stub packages on the system partition */
497    public final static String STUB_SUFFIX = "-Stub";
498
499    private static final int[] EMPTY_INT_ARRAY = new int[0];
500
501    private static final int TYPE_UNKNOWN = 0;
502    private static final int TYPE_ACTIVITY = 1;
503    private static final int TYPE_RECEIVER = 2;
504    private static final int TYPE_SERVICE = 3;
505    private static final int TYPE_PROVIDER = 4;
506    @IntDef(prefix = { "TYPE_" }, value = {
507            TYPE_UNKNOWN,
508            TYPE_ACTIVITY,
509            TYPE_RECEIVER,
510            TYPE_SERVICE,
511            TYPE_PROVIDER,
512    })
513    @Retention(RetentionPolicy.SOURCE)
514    public @interface ComponentType {}
515
516    /**
517     * Timeout (in milliseconds) after which the watchdog should declare that
518     * our handler thread is wedged.  The usual default for such things is one
519     * minute but we sometimes do very lengthy I/O operations on this thread,
520     * such as installing multi-gigabyte applications, so ours needs to be longer.
521     */
522    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
523
524    /**
525     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
526     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
527     * settings entry if available, otherwise we use the hardcoded default.  If it's been
528     * more than this long since the last fstrim, we force one during the boot sequence.
529     *
530     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
531     * one gets run at the next available charging+idle time.  This final mandatory
532     * no-fstrim check kicks in only of the other scheduling criteria is never met.
533     */
534    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
535
536    /**
537     * Whether verification is enabled by default.
538     */
539    private static final boolean DEFAULT_VERIFY_ENABLE = true;
540
541    /**
542     * The default maximum time to wait for the verification agent to return in
543     * milliseconds.
544     */
545    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
546
547    /**
548     * The default response for package verification timeout.
549     *
550     * This can be either PackageManager.VERIFICATION_ALLOW or
551     * PackageManager.VERIFICATION_REJECT.
552     */
553    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
554
555    public static final String PLATFORM_PACKAGE_NAME = "android";
556
557    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
558
559    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
560            DEFAULT_CONTAINER_PACKAGE,
561            "com.android.defcontainer.DefaultContainerService");
562
563    private static final String KILL_APP_REASON_GIDS_CHANGED =
564            "permission grant or revoke changed gids";
565
566    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
567            "permissions revoked";
568
569    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
570
571    private static final String PACKAGE_SCHEME = "package";
572
573    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
574
575    private static final String PRODUCT_OVERLAY_DIR = "/product/overlay";
576
577    private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob";
578
579    /** Canonical intent used to identify what counts as a "web browser" app */
580    private static final Intent sBrowserIntent;
581    static {
582        sBrowserIntent = new Intent();
583        sBrowserIntent.setAction(Intent.ACTION_VIEW);
584        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
585        sBrowserIntent.setData(Uri.parse("http:"));
586    }
587
588    /**
589     * The set of all protected actions [i.e. those actions for which a high priority
590     * intent filter is disallowed].
591     */
592    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
593    static {
594        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
595        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
596        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
597        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
598    }
599
600    // Compilation reasons.
601    public static final int REASON_FIRST_BOOT = 0;
602    public static final int REASON_BOOT = 1;
603    public static final int REASON_INSTALL = 2;
604    public static final int REASON_BACKGROUND_DEXOPT = 3;
605    public static final int REASON_AB_OTA = 4;
606    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
607    public static final int REASON_SHARED = 6;
608
609    public static final int REASON_LAST = REASON_SHARED;
610
611    /**
612     * Version number for the package parser cache. Increment this whenever the format or
613     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
614     */
615    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
616
617    /**
618     * Whether the package parser cache is enabled.
619     */
620    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
621
622    /**
623     * Permissions required in order to receive instant application lifecycle broadcasts.
624     */
625    private static final String[] INSTANT_APP_BROADCAST_PERMISSION =
626            new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS };
627
628    final ServiceThread mHandlerThread;
629
630    final PackageHandler mHandler;
631
632    private final ProcessLoggingHandler mProcessLoggingHandler;
633
634    /**
635     * Messages for {@link #mHandler} that need to wait for system ready before
636     * being dispatched.
637     */
638    private ArrayList<Message> mPostSystemReadyMessages;
639
640    final int mSdkVersion = Build.VERSION.SDK_INT;
641
642    final Context mContext;
643    final boolean mFactoryTest;
644    final boolean mOnlyCore;
645    final DisplayMetrics mMetrics;
646    final int mDefParseFlags;
647    final String[] mSeparateProcesses;
648    final boolean mIsUpgrade;
649    final boolean mIsPreNUpgrade;
650    final boolean mIsPreNMR1Upgrade;
651
652    // Have we told the Activity Manager to whitelist the default container service by uid yet?
653    @GuardedBy("mPackages")
654    boolean mDefaultContainerWhitelisted = false;
655
656    @GuardedBy("mPackages")
657    private boolean mDexOptDialogShown;
658
659    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
660    // LOCK HELD.  Can be called with mInstallLock held.
661    @GuardedBy("mInstallLock")
662    final Installer mInstaller;
663
664    /** Directory where installed applications are stored */
665    private static final File sAppInstallDir =
666            new File(Environment.getDataDirectory(), "app");
667    /** Directory where installed application's 32-bit native libraries are copied. */
668    private static final File sAppLib32InstallDir =
669            new File(Environment.getDataDirectory(), "app-lib");
670    /** Directory where code and non-resource assets of forward-locked applications are stored */
671    private static final File sDrmAppPrivateInstallDir =
672            new File(Environment.getDataDirectory(), "app-private");
673
674    // ----------------------------------------------------------------
675
676    // Lock for state used when installing and doing other long running
677    // operations.  Methods that must be called with this lock held have
678    // the suffix "LI".
679    final Object mInstallLock = new Object();
680
681    // ----------------------------------------------------------------
682
683    // Keys are String (package name), values are Package.  This also serves
684    // as the lock for the global state.  Methods that must be called with
685    // this lock held have the prefix "LP".
686    @GuardedBy("mPackages")
687    final ArrayMap<String, PackageParser.Package> mPackages =
688            new ArrayMap<String, PackageParser.Package>();
689
690    final ArrayMap<String, Set<String>> mKnownCodebase =
691            new ArrayMap<String, Set<String>>();
692
693    // Keys are isolated uids and values are the uid of the application
694    // that created the isolated proccess.
695    @GuardedBy("mPackages")
696    final SparseIntArray mIsolatedOwners = new SparseIntArray();
697
698    /**
699     * Tracks new system packages [received in an OTA] that we expect to
700     * find updated user-installed versions. Keys are package name, values
701     * are package location.
702     */
703    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
704    /**
705     * Tracks high priority intent filters for protected actions. During boot, certain
706     * filter actions are protected and should never be allowed to have a high priority
707     * intent filter for them. However, there is one, and only one exception -- the
708     * setup wizard. It must be able to define a high priority intent filter for these
709     * actions to ensure there are no escapes from the wizard. We need to delay processing
710     * of these during boot as we need to look at all of the system packages in order
711     * to know which component is the setup wizard.
712     */
713    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
714    /**
715     * Whether or not processing protected filters should be deferred.
716     */
717    private boolean mDeferProtectedFilters = true;
718
719    /**
720     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
721     */
722    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
723    /**
724     * Whether or not system app permissions should be promoted from install to runtime.
725     */
726    boolean mPromoteSystemApps;
727
728    @GuardedBy("mPackages")
729    final Settings mSettings;
730
731    /**
732     * Set of package names that are currently "frozen", which means active
733     * surgery is being done on the code/data for that package. The platform
734     * will refuse to launch frozen packages to avoid race conditions.
735     *
736     * @see PackageFreezer
737     */
738    @GuardedBy("mPackages")
739    final ArraySet<String> mFrozenPackages = new ArraySet<>();
740
741    final ProtectedPackages mProtectedPackages;
742
743    @GuardedBy("mLoadedVolumes")
744    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
745
746    boolean mFirstBoot;
747
748    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
749
750    @GuardedBy("mAvailableFeatures")
751    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
752
753    private final InstantAppRegistry mInstantAppRegistry;
754
755    @GuardedBy("mPackages")
756    int mChangedPackagesSequenceNumber;
757    /**
758     * List of changed [installed, removed or updated] packages.
759     * mapping from user id -> sequence number -> package name
760     */
761    @GuardedBy("mPackages")
762    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
763    /**
764     * The sequence number of the last change to a package.
765     * mapping from user id -> package name -> sequence number
766     */
767    @GuardedBy("mPackages")
768    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
769
770    @GuardedBy("mPackages")
771    final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>();
772
773    class PackageParserCallback implements PackageParser.Callback {
774        @Override public final boolean hasFeature(String feature) {
775            return PackageManagerService.this.hasSystemFeature(feature, 0);
776        }
777
778        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
779                Collection<PackageParser.Package> allPackages, String targetPackageName) {
780            List<PackageParser.Package> overlayPackages = null;
781            for (PackageParser.Package p : allPackages) {
782                if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) {
783                    if (overlayPackages == null) {
784                        overlayPackages = new ArrayList<PackageParser.Package>();
785                    }
786                    overlayPackages.add(p);
787                }
788            }
789            if (overlayPackages != null) {
790                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
791                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
792                        return p1.mOverlayPriority - p2.mOverlayPriority;
793                    }
794                };
795                Collections.sort(overlayPackages, cmp);
796            }
797            return overlayPackages;
798        }
799
800        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
801                String targetPackageName, String targetPath) {
802            if ("android".equals(targetPackageName)) {
803                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
804                // native AssetManager.
805                return null;
806            }
807            List<PackageParser.Package> overlayPackages =
808                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
809            if (overlayPackages == null || overlayPackages.isEmpty()) {
810                return null;
811            }
812            List<String> overlayPathList = null;
813            for (PackageParser.Package overlayPackage : overlayPackages) {
814                if (targetPath == null) {
815                    if (overlayPathList == null) {
816                        overlayPathList = new ArrayList<String>();
817                    }
818                    overlayPathList.add(overlayPackage.baseCodePath);
819                    continue;
820                }
821
822                try {
823                    // Creates idmaps for system to parse correctly the Android manifest of the
824                    // target package.
825                    //
826                    // OverlayManagerService will update each of them with a correct gid from its
827                    // target package app id.
828                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
829                            UserHandle.getSharedAppGid(
830                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
831                    if (overlayPathList == null) {
832                        overlayPathList = new ArrayList<String>();
833                    }
834                    overlayPathList.add(overlayPackage.baseCodePath);
835                } catch (InstallerException e) {
836                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
837                            overlayPackage.baseCodePath);
838                }
839            }
840            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
841        }
842
843        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
844            synchronized (mPackages) {
845                return getStaticOverlayPathsLocked(
846                        mPackages.values(), targetPackageName, targetPath);
847            }
848        }
849
850        @Override public final String[] getOverlayApks(String targetPackageName) {
851            return getStaticOverlayPaths(targetPackageName, null);
852        }
853
854        @Override public final String[] getOverlayPaths(String targetPackageName,
855                String targetPath) {
856            return getStaticOverlayPaths(targetPackageName, targetPath);
857        }
858    }
859
860    class ParallelPackageParserCallback extends PackageParserCallback {
861        List<PackageParser.Package> mOverlayPackages = null;
862
863        void findStaticOverlayPackages() {
864            synchronized (mPackages) {
865                for (PackageParser.Package p : mPackages.values()) {
866                    if (p.mOverlayIsStatic) {
867                        if (mOverlayPackages == null) {
868                            mOverlayPackages = new ArrayList<PackageParser.Package>();
869                        }
870                        mOverlayPackages.add(p);
871                    }
872                }
873            }
874        }
875
876        @Override
877        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
878            // We can trust mOverlayPackages without holding mPackages because package uninstall
879            // can't happen while running parallel parsing.
880            // Moreover holding mPackages on each parsing thread causes dead-lock.
881            return mOverlayPackages == null ? null :
882                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
883        }
884    }
885
886    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
887    final ParallelPackageParserCallback mParallelPackageParserCallback =
888            new ParallelPackageParserCallback();
889
890    public static final class SharedLibraryEntry {
891        public final @Nullable String path;
892        public final @Nullable String apk;
893        public final @NonNull SharedLibraryInfo info;
894
895        SharedLibraryEntry(String _path, String _apk, String name, long version, int type,
896                String declaringPackageName, long declaringPackageVersionCode) {
897            path = _path;
898            apk = _apk;
899            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
900                    declaringPackageName, declaringPackageVersionCode), null);
901        }
902    }
903
904    // Currently known shared libraries.
905    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
906    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
907            new ArrayMap<>();
908
909    // All available activities, for your resolving pleasure.
910    final ActivityIntentResolver mActivities =
911            new ActivityIntentResolver();
912
913    // All available receivers, for your resolving pleasure.
914    final ActivityIntentResolver mReceivers =
915            new ActivityIntentResolver();
916
917    // All available services, for your resolving pleasure.
918    final ServiceIntentResolver mServices = new ServiceIntentResolver();
919
920    // All available providers, for your resolving pleasure.
921    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
922
923    // Mapping from provider base names (first directory in content URI codePath)
924    // to the provider information.
925    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
926            new ArrayMap<String, PackageParser.Provider>();
927
928    // Mapping from instrumentation class names to info about them.
929    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
930            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
931
932    // Packages whose data we have transfered into another package, thus
933    // should no longer exist.
934    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
935
936    // Broadcast actions that are only available to the system.
937    @GuardedBy("mProtectedBroadcasts")
938    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
939
940    /** List of packages waiting for verification. */
941    final SparseArray<PackageVerificationState> mPendingVerification
942            = new SparseArray<PackageVerificationState>();
943
944    final PackageInstallerService mInstallerService;
945
946    final ArtManagerService mArtManagerService;
947
948    private final PackageDexOptimizer mPackageDexOptimizer;
949    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
950    // is used by other apps).
951    private final DexManager mDexManager;
952
953    private AtomicInteger mNextMoveId = new AtomicInteger();
954    private final MoveCallbacks mMoveCallbacks;
955
956    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
957
958    // Cache of users who need badging.
959    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
960
961    /** Token for keys in mPendingVerification. */
962    private int mPendingVerificationToken = 0;
963
964    volatile boolean mSystemReady;
965    volatile boolean mSafeMode;
966    volatile boolean mHasSystemUidErrors;
967    private volatile boolean mEphemeralAppsDisabled;
968
969    ApplicationInfo mAndroidApplication;
970    final ActivityInfo mResolveActivity = new ActivityInfo();
971    final ResolveInfo mResolveInfo = new ResolveInfo();
972    ComponentName mResolveComponentName;
973    PackageParser.Package mPlatformPackage;
974    ComponentName mCustomResolverComponentName;
975
976    boolean mResolverReplaced = false;
977
978    private final @Nullable ComponentName mIntentFilterVerifierComponent;
979    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
980
981    private int mIntentFilterVerificationToken = 0;
982
983    /** The service connection to the ephemeral resolver */
984    final EphemeralResolverConnection mInstantAppResolverConnection;
985    /** Component used to show resolver settings for Instant Apps */
986    final ComponentName mInstantAppResolverSettingsComponent;
987
988    /** Activity used to install instant applications */
989    ActivityInfo mInstantAppInstallerActivity;
990    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
991
992    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
993            = new SparseArray<IntentFilterVerificationState>();
994
995    // TODO remove this and go through mPermissonManager directly
996    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
997    private final PermissionManagerInternal mPermissionManager;
998
999    // List of packages names to keep cached, even if they are uninstalled for all users
1000    private List<String> mKeepUninstalledPackages;
1001
1002    private UserManagerInternal mUserManagerInternal;
1003    private ActivityManagerInternal mActivityManagerInternal;
1004
1005    private DeviceIdleController.LocalService mDeviceIdleController;
1006
1007    private File mCacheDir;
1008
1009    private Future<?> mPrepareAppDataFuture;
1010
1011    private static class IFVerificationParams {
1012        PackageParser.Package pkg;
1013        boolean replacing;
1014        int userId;
1015        int verifierUid;
1016
1017        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1018                int _userId, int _verifierUid) {
1019            pkg = _pkg;
1020            replacing = _replacing;
1021            userId = _userId;
1022            replacing = _replacing;
1023            verifierUid = _verifierUid;
1024        }
1025    }
1026
1027    private interface IntentFilterVerifier<T extends IntentFilter> {
1028        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1029                                               T filter, String packageName);
1030        void startVerifications(int userId);
1031        void receiveVerificationResponse(int verificationId);
1032    }
1033
1034    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1035        private Context mContext;
1036        private ComponentName mIntentFilterVerifierComponent;
1037        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1038
1039        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1040            mContext = context;
1041            mIntentFilterVerifierComponent = verifierComponent;
1042        }
1043
1044        private String getDefaultScheme() {
1045            return IntentFilter.SCHEME_HTTPS;
1046        }
1047
1048        @Override
1049        public void startVerifications(int userId) {
1050            // Launch verifications requests
1051            int count = mCurrentIntentFilterVerifications.size();
1052            for (int n=0; n<count; n++) {
1053                int verificationId = mCurrentIntentFilterVerifications.get(n);
1054                final IntentFilterVerificationState ivs =
1055                        mIntentFilterVerificationStates.get(verificationId);
1056
1057                String packageName = ivs.getPackageName();
1058
1059                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1060                final int filterCount = filters.size();
1061                ArraySet<String> domainsSet = new ArraySet<>();
1062                for (int m=0; m<filterCount; m++) {
1063                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1064                    domainsSet.addAll(filter.getHostsList());
1065                }
1066                synchronized (mPackages) {
1067                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1068                            packageName, domainsSet) != null) {
1069                        scheduleWriteSettingsLocked();
1070                    }
1071                }
1072                sendVerificationRequest(verificationId, ivs);
1073            }
1074            mCurrentIntentFilterVerifications.clear();
1075        }
1076
1077        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1078            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1079            verificationIntent.putExtra(
1080                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1081                    verificationId);
1082            verificationIntent.putExtra(
1083                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1084                    getDefaultScheme());
1085            verificationIntent.putExtra(
1086                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1087                    ivs.getHostsString());
1088            verificationIntent.putExtra(
1089                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1090                    ivs.getPackageName());
1091            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1092            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1093
1094            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1095            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1096                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1097                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1098
1099            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1100            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1101                    "Sending IntentFilter verification broadcast");
1102        }
1103
1104        public void receiveVerificationResponse(int verificationId) {
1105            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1106
1107            final boolean verified = ivs.isVerified();
1108
1109            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1110            final int count = filters.size();
1111            if (DEBUG_DOMAIN_VERIFICATION) {
1112                Slog.i(TAG, "Received verification response " + verificationId
1113                        + " for " + count + " filters, verified=" + verified);
1114            }
1115            for (int n=0; n<count; n++) {
1116                PackageParser.ActivityIntentInfo filter = filters.get(n);
1117                filter.setVerified(verified);
1118
1119                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1120                        + " verified with result:" + verified + " and hosts:"
1121                        + ivs.getHostsString());
1122            }
1123
1124            mIntentFilterVerificationStates.remove(verificationId);
1125
1126            final String packageName = ivs.getPackageName();
1127            IntentFilterVerificationInfo ivi = null;
1128
1129            synchronized (mPackages) {
1130                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1131            }
1132            if (ivi == null) {
1133                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1134                        + verificationId + " packageName:" + packageName);
1135                return;
1136            }
1137            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1138                    "Updating IntentFilterVerificationInfo for package " + packageName
1139                            +" verificationId:" + verificationId);
1140
1141            synchronized (mPackages) {
1142                if (verified) {
1143                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1144                } else {
1145                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1146                }
1147                scheduleWriteSettingsLocked();
1148
1149                final int userId = ivs.getUserId();
1150                if (userId != UserHandle.USER_ALL) {
1151                    final int userStatus =
1152                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1153
1154                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1155                    boolean needUpdate = false;
1156
1157                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1158                    // already been set by the User thru the Disambiguation dialog
1159                    switch (userStatus) {
1160                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1161                            if (verified) {
1162                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1163                            } else {
1164                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1165                            }
1166                            needUpdate = true;
1167                            break;
1168
1169                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1170                            if (verified) {
1171                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1172                                needUpdate = true;
1173                            }
1174                            break;
1175
1176                        default:
1177                            // Nothing to do
1178                    }
1179
1180                    if (needUpdate) {
1181                        mSettings.updateIntentFilterVerificationStatusLPw(
1182                                packageName, updatedStatus, userId);
1183                        scheduleWritePackageRestrictionsLocked(userId);
1184                    }
1185                }
1186            }
1187        }
1188
1189        @Override
1190        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1191                    ActivityIntentInfo filter, String packageName) {
1192            if (!hasValidDomains(filter)) {
1193                return false;
1194            }
1195            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1196            if (ivs == null) {
1197                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1198                        packageName);
1199            }
1200            if (DEBUG_DOMAIN_VERIFICATION) {
1201                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1202            }
1203            ivs.addFilter(filter);
1204            return true;
1205        }
1206
1207        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1208                int userId, int verificationId, String packageName) {
1209            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1210                    verifierUid, userId, packageName);
1211            ivs.setPendingState();
1212            synchronized (mPackages) {
1213                mIntentFilterVerificationStates.append(verificationId, ivs);
1214                mCurrentIntentFilterVerifications.add(verificationId);
1215            }
1216            return ivs;
1217        }
1218    }
1219
1220    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1221        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1222                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1223                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1224    }
1225
1226    // Set of pending broadcasts for aggregating enable/disable of components.
1227    static class PendingPackageBroadcasts {
1228        // for each user id, a map of <package name -> components within that package>
1229        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1230
1231        public PendingPackageBroadcasts() {
1232            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1233        }
1234
1235        public ArrayList<String> get(int userId, String packageName) {
1236            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1237            return packages.get(packageName);
1238        }
1239
1240        public void put(int userId, String packageName, ArrayList<String> components) {
1241            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1242            packages.put(packageName, components);
1243        }
1244
1245        public void remove(int userId, String packageName) {
1246            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1247            if (packages != null) {
1248                packages.remove(packageName);
1249            }
1250        }
1251
1252        public void remove(int userId) {
1253            mUidMap.remove(userId);
1254        }
1255
1256        public int userIdCount() {
1257            return mUidMap.size();
1258        }
1259
1260        public int userIdAt(int n) {
1261            return mUidMap.keyAt(n);
1262        }
1263
1264        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1265            return mUidMap.get(userId);
1266        }
1267
1268        public int size() {
1269            // total number of pending broadcast entries across all userIds
1270            int num = 0;
1271            for (int i = 0; i< mUidMap.size(); i++) {
1272                num += mUidMap.valueAt(i).size();
1273            }
1274            return num;
1275        }
1276
1277        public void clear() {
1278            mUidMap.clear();
1279        }
1280
1281        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1282            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1283            if (map == null) {
1284                map = new ArrayMap<String, ArrayList<String>>();
1285                mUidMap.put(userId, map);
1286            }
1287            return map;
1288        }
1289    }
1290    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1291
1292    // Service Connection to remote media container service to copy
1293    // package uri's from external media onto secure containers
1294    // or internal storage.
1295    private IMediaContainerService mContainerService = null;
1296
1297    static final int SEND_PENDING_BROADCAST = 1;
1298    static final int MCS_BOUND = 3;
1299    static final int END_COPY = 4;
1300    static final int INIT_COPY = 5;
1301    static final int MCS_UNBIND = 6;
1302    static final int START_CLEANING_PACKAGE = 7;
1303    static final int FIND_INSTALL_LOC = 8;
1304    static final int POST_INSTALL = 9;
1305    static final int MCS_RECONNECT = 10;
1306    static final int MCS_GIVE_UP = 11;
1307    static final int WRITE_SETTINGS = 13;
1308    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1309    static final int PACKAGE_VERIFIED = 15;
1310    static final int CHECK_PENDING_VERIFICATION = 16;
1311    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1312    static final int INTENT_FILTER_VERIFIED = 18;
1313    static final int WRITE_PACKAGE_LIST = 19;
1314    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1315
1316    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1317
1318    // Delay time in millisecs
1319    static final int BROADCAST_DELAY = 10 * 1000;
1320
1321    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1322            2 * 60 * 60 * 1000L; /* two hours */
1323
1324    static UserManagerService sUserManager;
1325
1326    // Stores a list of users whose package restrictions file needs to be updated
1327    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1328
1329    final private DefaultContainerConnection mDefContainerConn =
1330            new DefaultContainerConnection();
1331    class DefaultContainerConnection implements ServiceConnection {
1332        public void onServiceConnected(ComponentName name, IBinder service) {
1333            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1334            final IMediaContainerService imcs = IMediaContainerService.Stub
1335                    .asInterface(Binder.allowBlocking(service));
1336            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1337        }
1338
1339        public void onServiceDisconnected(ComponentName name) {
1340            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1341        }
1342    }
1343
1344    // Recordkeeping of restore-after-install operations that are currently in flight
1345    // between the Package Manager and the Backup Manager
1346    static class PostInstallData {
1347        public InstallArgs args;
1348        public PackageInstalledInfo res;
1349
1350        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1351            args = _a;
1352            res = _r;
1353        }
1354    }
1355
1356    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1357    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1358
1359    // XML tags for backup/restore of various bits of state
1360    private static final String TAG_PREFERRED_BACKUP = "pa";
1361    private static final String TAG_DEFAULT_APPS = "da";
1362    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1363
1364    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1365    private static final String TAG_ALL_GRANTS = "rt-grants";
1366    private static final String TAG_GRANT = "grant";
1367    private static final String ATTR_PACKAGE_NAME = "pkg";
1368
1369    private static final String TAG_PERMISSION = "perm";
1370    private static final String ATTR_PERMISSION_NAME = "name";
1371    private static final String ATTR_IS_GRANTED = "g";
1372    private static final String ATTR_USER_SET = "set";
1373    private static final String ATTR_USER_FIXED = "fixed";
1374    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1375
1376    // System/policy permission grants are not backed up
1377    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1378            FLAG_PERMISSION_POLICY_FIXED
1379            | FLAG_PERMISSION_SYSTEM_FIXED
1380            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1381
1382    // And we back up these user-adjusted states
1383    private static final int USER_RUNTIME_GRANT_MASK =
1384            FLAG_PERMISSION_USER_SET
1385            | FLAG_PERMISSION_USER_FIXED
1386            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1387
1388    final @Nullable String mRequiredVerifierPackage;
1389    final @NonNull String mRequiredInstallerPackage;
1390    final @NonNull String mRequiredUninstallerPackage;
1391    final @Nullable String mSetupWizardPackage;
1392    final @Nullable String mStorageManagerPackage;
1393    final @NonNull String mServicesSystemSharedLibraryPackageName;
1394    final @NonNull String mSharedSystemSharedLibraryPackageName;
1395
1396    private final PackageUsage mPackageUsage = new PackageUsage();
1397    private final CompilerStats mCompilerStats = new CompilerStats();
1398
1399    class PackageHandler extends Handler {
1400        private boolean mBound = false;
1401        final ArrayList<HandlerParams> mPendingInstalls =
1402            new ArrayList<HandlerParams>();
1403
1404        private boolean connectToService() {
1405            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1406                    " DefaultContainerService");
1407            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1408            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1409            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1410                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1411                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1412                mBound = true;
1413                return true;
1414            }
1415            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1416            return false;
1417        }
1418
1419        private void disconnectService() {
1420            mContainerService = null;
1421            mBound = false;
1422            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1423            mContext.unbindService(mDefContainerConn);
1424            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1425        }
1426
1427        PackageHandler(Looper looper) {
1428            super(looper);
1429        }
1430
1431        public void handleMessage(Message msg) {
1432            try {
1433                doHandleMessage(msg);
1434            } finally {
1435                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1436            }
1437        }
1438
1439        void doHandleMessage(Message msg) {
1440            switch (msg.what) {
1441                case INIT_COPY: {
1442                    HandlerParams params = (HandlerParams) msg.obj;
1443                    int idx = mPendingInstalls.size();
1444                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1445                    // If a bind was already initiated we dont really
1446                    // need to do anything. The pending install
1447                    // will be processed later on.
1448                    if (!mBound) {
1449                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1450                                System.identityHashCode(mHandler));
1451                        // If this is the only one pending we might
1452                        // have to bind to the service again.
1453                        if (!connectToService()) {
1454                            Slog.e(TAG, "Failed to bind to media container service");
1455                            params.serviceError();
1456                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1457                                    System.identityHashCode(mHandler));
1458                            if (params.traceMethod != null) {
1459                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1460                                        params.traceCookie);
1461                            }
1462                            return;
1463                        } else {
1464                            // Once we bind to the service, the first
1465                            // pending request will be processed.
1466                            mPendingInstalls.add(idx, params);
1467                        }
1468                    } else {
1469                        mPendingInstalls.add(idx, params);
1470                        // Already bound to the service. Just make
1471                        // sure we trigger off processing the first request.
1472                        if (idx == 0) {
1473                            mHandler.sendEmptyMessage(MCS_BOUND);
1474                        }
1475                    }
1476                    break;
1477                }
1478                case MCS_BOUND: {
1479                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1480                    if (msg.obj != null) {
1481                        mContainerService = (IMediaContainerService) msg.obj;
1482                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1483                                System.identityHashCode(mHandler));
1484                    }
1485                    if (mContainerService == null) {
1486                        if (!mBound) {
1487                            // Something seriously wrong since we are not bound and we are not
1488                            // waiting for connection. Bail out.
1489                            Slog.e(TAG, "Cannot bind to media container service");
1490                            for (HandlerParams params : mPendingInstalls) {
1491                                // Indicate service bind error
1492                                params.serviceError();
1493                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1494                                        System.identityHashCode(params));
1495                                if (params.traceMethod != null) {
1496                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1497                                            params.traceMethod, params.traceCookie);
1498                                }
1499                                return;
1500                            }
1501                            mPendingInstalls.clear();
1502                        } else {
1503                            Slog.w(TAG, "Waiting to connect to media container service");
1504                        }
1505                    } else if (mPendingInstalls.size() > 0) {
1506                        HandlerParams params = mPendingInstalls.get(0);
1507                        if (params != null) {
1508                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1509                                    System.identityHashCode(params));
1510                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1511                            if (params.startCopy()) {
1512                                // We are done...  look for more work or to
1513                                // go idle.
1514                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1515                                        "Checking for more work or unbind...");
1516                                // Delete pending install
1517                                if (mPendingInstalls.size() > 0) {
1518                                    mPendingInstalls.remove(0);
1519                                }
1520                                if (mPendingInstalls.size() == 0) {
1521                                    if (mBound) {
1522                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1523                                                "Posting delayed MCS_UNBIND");
1524                                        removeMessages(MCS_UNBIND);
1525                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1526                                        // Unbind after a little delay, to avoid
1527                                        // continual thrashing.
1528                                        sendMessageDelayed(ubmsg, 10000);
1529                                    }
1530                                } else {
1531                                    // There are more pending requests in queue.
1532                                    // Just post MCS_BOUND message to trigger processing
1533                                    // of next pending install.
1534                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1535                                            "Posting MCS_BOUND for next work");
1536                                    mHandler.sendEmptyMessage(MCS_BOUND);
1537                                }
1538                            }
1539                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1540                        }
1541                    } else {
1542                        // Should never happen ideally.
1543                        Slog.w(TAG, "Empty queue");
1544                    }
1545                    break;
1546                }
1547                case MCS_RECONNECT: {
1548                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1549                    if (mPendingInstalls.size() > 0) {
1550                        if (mBound) {
1551                            disconnectService();
1552                        }
1553                        if (!connectToService()) {
1554                            Slog.e(TAG, "Failed to bind to media container service");
1555                            for (HandlerParams params : mPendingInstalls) {
1556                                // Indicate service bind error
1557                                params.serviceError();
1558                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1559                                        System.identityHashCode(params));
1560                            }
1561                            mPendingInstalls.clear();
1562                        }
1563                    }
1564                    break;
1565                }
1566                case MCS_UNBIND: {
1567                    // If there is no actual work left, then time to unbind.
1568                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1569
1570                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1571                        if (mBound) {
1572                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1573
1574                            disconnectService();
1575                        }
1576                    } else if (mPendingInstalls.size() > 0) {
1577                        // There are more pending requests in queue.
1578                        // Just post MCS_BOUND message to trigger processing
1579                        // of next pending install.
1580                        mHandler.sendEmptyMessage(MCS_BOUND);
1581                    }
1582
1583                    break;
1584                }
1585                case MCS_GIVE_UP: {
1586                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1587                    HandlerParams params = mPendingInstalls.remove(0);
1588                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1589                            System.identityHashCode(params));
1590                    break;
1591                }
1592                case SEND_PENDING_BROADCAST: {
1593                    String packages[];
1594                    ArrayList<String> components[];
1595                    int size = 0;
1596                    int uids[];
1597                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1598                    synchronized (mPackages) {
1599                        if (mPendingBroadcasts == null) {
1600                            return;
1601                        }
1602                        size = mPendingBroadcasts.size();
1603                        if (size <= 0) {
1604                            // Nothing to be done. Just return
1605                            return;
1606                        }
1607                        packages = new String[size];
1608                        components = new ArrayList[size];
1609                        uids = new int[size];
1610                        int i = 0;  // filling out the above arrays
1611
1612                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1613                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1614                            Iterator<Map.Entry<String, ArrayList<String>>> it
1615                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1616                                            .entrySet().iterator();
1617                            while (it.hasNext() && i < size) {
1618                                Map.Entry<String, ArrayList<String>> ent = it.next();
1619                                packages[i] = ent.getKey();
1620                                components[i] = ent.getValue();
1621                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1622                                uids[i] = (ps != null)
1623                                        ? UserHandle.getUid(packageUserId, ps.appId)
1624                                        : -1;
1625                                i++;
1626                            }
1627                        }
1628                        size = i;
1629                        mPendingBroadcasts.clear();
1630                    }
1631                    // Send broadcasts
1632                    for (int i = 0; i < size; i++) {
1633                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1634                    }
1635                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1636                    break;
1637                }
1638                case START_CLEANING_PACKAGE: {
1639                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1640                    final String packageName = (String)msg.obj;
1641                    final int userId = msg.arg1;
1642                    final boolean andCode = msg.arg2 != 0;
1643                    synchronized (mPackages) {
1644                        if (userId == UserHandle.USER_ALL) {
1645                            int[] users = sUserManager.getUserIds();
1646                            for (int user : users) {
1647                                mSettings.addPackageToCleanLPw(
1648                                        new PackageCleanItem(user, packageName, andCode));
1649                            }
1650                        } else {
1651                            mSettings.addPackageToCleanLPw(
1652                                    new PackageCleanItem(userId, packageName, andCode));
1653                        }
1654                    }
1655                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1656                    startCleaningPackages();
1657                } break;
1658                case POST_INSTALL: {
1659                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1660
1661                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1662                    final boolean didRestore = (msg.arg2 != 0);
1663                    mRunningInstalls.delete(msg.arg1);
1664
1665                    if (data != null) {
1666                        InstallArgs args = data.args;
1667                        PackageInstalledInfo parentRes = data.res;
1668
1669                        final boolean grantPermissions = (args.installFlags
1670                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1671                        final boolean killApp = (args.installFlags
1672                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1673                        final boolean virtualPreload = ((args.installFlags
1674                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1675                        final String[] grantedPermissions = args.installGrantPermissions;
1676
1677                        // Handle the parent package
1678                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1679                                virtualPreload, grantedPermissions, didRestore,
1680                                args.installerPackageName, args.observer);
1681
1682                        // Handle the child packages
1683                        final int childCount = (parentRes.addedChildPackages != null)
1684                                ? parentRes.addedChildPackages.size() : 0;
1685                        for (int i = 0; i < childCount; i++) {
1686                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1687                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1688                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1689                                    args.installerPackageName, args.observer);
1690                        }
1691
1692                        // Log tracing if needed
1693                        if (args.traceMethod != null) {
1694                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1695                                    args.traceCookie);
1696                        }
1697                    } else {
1698                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1699                    }
1700
1701                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1702                } break;
1703                case WRITE_SETTINGS: {
1704                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1705                    synchronized (mPackages) {
1706                        removeMessages(WRITE_SETTINGS);
1707                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1708                        mSettings.writeLPr();
1709                        mDirtyUsers.clear();
1710                    }
1711                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1712                } break;
1713                case WRITE_PACKAGE_RESTRICTIONS: {
1714                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1715                    synchronized (mPackages) {
1716                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1717                        for (int userId : mDirtyUsers) {
1718                            mSettings.writePackageRestrictionsLPr(userId);
1719                        }
1720                        mDirtyUsers.clear();
1721                    }
1722                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1723                } break;
1724                case WRITE_PACKAGE_LIST: {
1725                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1726                    synchronized (mPackages) {
1727                        removeMessages(WRITE_PACKAGE_LIST);
1728                        mSettings.writePackageListLPr(msg.arg1);
1729                    }
1730                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1731                } break;
1732                case CHECK_PENDING_VERIFICATION: {
1733                    final int verificationId = msg.arg1;
1734                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1735
1736                    if ((state != null) && !state.timeoutExtended()) {
1737                        final InstallArgs args = state.getInstallArgs();
1738                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1739
1740                        Slog.i(TAG, "Verification timed out for " + originUri);
1741                        mPendingVerification.remove(verificationId);
1742
1743                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1744
1745                        final UserHandle user = args.getUser();
1746                        if (getDefaultVerificationResponse(user)
1747                                == PackageManager.VERIFICATION_ALLOW) {
1748                            Slog.i(TAG, "Continuing with installation of " + originUri);
1749                            state.setVerifierResponse(Binder.getCallingUid(),
1750                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1751                            broadcastPackageVerified(verificationId, originUri,
1752                                    PackageManager.VERIFICATION_ALLOW, user);
1753                            try {
1754                                ret = args.copyApk(mContainerService, true);
1755                            } catch (RemoteException e) {
1756                                Slog.e(TAG, "Could not contact the ContainerService");
1757                            }
1758                        } else {
1759                            broadcastPackageVerified(verificationId, originUri,
1760                                    PackageManager.VERIFICATION_REJECT, user);
1761                        }
1762
1763                        Trace.asyncTraceEnd(
1764                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1765
1766                        processPendingInstall(args, ret);
1767                        mHandler.sendEmptyMessage(MCS_UNBIND);
1768                    }
1769                    break;
1770                }
1771                case PACKAGE_VERIFIED: {
1772                    final int verificationId = msg.arg1;
1773
1774                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1775                    if (state == null) {
1776                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1777                        break;
1778                    }
1779
1780                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1781
1782                    state.setVerifierResponse(response.callerUid, response.code);
1783
1784                    if (state.isVerificationComplete()) {
1785                        mPendingVerification.remove(verificationId);
1786
1787                        final InstallArgs args = state.getInstallArgs();
1788                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1789
1790                        int ret;
1791                        if (state.isInstallAllowed()) {
1792                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1793                            broadcastPackageVerified(verificationId, originUri,
1794                                    response.code, state.getInstallArgs().getUser());
1795                            try {
1796                                ret = args.copyApk(mContainerService, true);
1797                            } catch (RemoteException e) {
1798                                Slog.e(TAG, "Could not contact the ContainerService");
1799                            }
1800                        } else {
1801                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1802                        }
1803
1804                        Trace.asyncTraceEnd(
1805                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1806
1807                        processPendingInstall(args, ret);
1808                        mHandler.sendEmptyMessage(MCS_UNBIND);
1809                    }
1810
1811                    break;
1812                }
1813                case START_INTENT_FILTER_VERIFICATIONS: {
1814                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1815                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1816                            params.replacing, params.pkg);
1817                    break;
1818                }
1819                case INTENT_FILTER_VERIFIED: {
1820                    final int verificationId = msg.arg1;
1821
1822                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1823                            verificationId);
1824                    if (state == null) {
1825                        Slog.w(TAG, "Invalid IntentFilter verification token "
1826                                + verificationId + " received");
1827                        break;
1828                    }
1829
1830                    final int userId = state.getUserId();
1831
1832                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1833                            "Processing IntentFilter verification with token:"
1834                            + verificationId + " and userId:" + userId);
1835
1836                    final IntentFilterVerificationResponse response =
1837                            (IntentFilterVerificationResponse) msg.obj;
1838
1839                    state.setVerifierResponse(response.callerUid, response.code);
1840
1841                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1842                            "IntentFilter verification with token:" + verificationId
1843                            + " and userId:" + userId
1844                            + " is settings verifier response with response code:"
1845                            + response.code);
1846
1847                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1848                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1849                                + response.getFailedDomainsString());
1850                    }
1851
1852                    if (state.isVerificationComplete()) {
1853                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1854                    } else {
1855                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1856                                "IntentFilter verification with token:" + verificationId
1857                                + " was not said to be complete");
1858                    }
1859
1860                    break;
1861                }
1862                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1863                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1864                            mInstantAppResolverConnection,
1865                            (InstantAppRequest) msg.obj,
1866                            mInstantAppInstallerActivity,
1867                            mHandler);
1868                }
1869            }
1870        }
1871    }
1872
1873    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1874        @Override
1875        public void onGidsChanged(int appId, int userId) {
1876            mHandler.post(new Runnable() {
1877                @Override
1878                public void run() {
1879                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1880                }
1881            });
1882        }
1883        @Override
1884        public void onPermissionGranted(int uid, int userId) {
1885            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1886
1887            // Not critical; if this is lost, the application has to request again.
1888            synchronized (mPackages) {
1889                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1890            }
1891        }
1892        @Override
1893        public void onInstallPermissionGranted() {
1894            synchronized (mPackages) {
1895                scheduleWriteSettingsLocked();
1896            }
1897        }
1898        @Override
1899        public void onPermissionRevoked(int uid, int userId) {
1900            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1901
1902            synchronized (mPackages) {
1903                // Critical; after this call the application should never have the permission
1904                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1905            }
1906
1907            final int appId = UserHandle.getAppId(uid);
1908            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1909        }
1910        @Override
1911        public void onInstallPermissionRevoked() {
1912            synchronized (mPackages) {
1913                scheduleWriteSettingsLocked();
1914            }
1915        }
1916        @Override
1917        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1918            synchronized (mPackages) {
1919                for (int userId : updatedUserIds) {
1920                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1921                }
1922            }
1923        }
1924        @Override
1925        public void onInstallPermissionUpdated() {
1926            synchronized (mPackages) {
1927                scheduleWriteSettingsLocked();
1928            }
1929        }
1930        @Override
1931        public void onPermissionRemoved() {
1932            synchronized (mPackages) {
1933                mSettings.writeLPr();
1934            }
1935        }
1936    };
1937
1938    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1939            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1940            boolean launchedForRestore, String installerPackage,
1941            IPackageInstallObserver2 installObserver) {
1942        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1943            // Send the removed broadcasts
1944            if (res.removedInfo != null) {
1945                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1946            }
1947
1948            // Now that we successfully installed the package, grant runtime
1949            // permissions if requested before broadcasting the install. Also
1950            // for legacy apps in permission review mode we clear the permission
1951            // review flag which is used to emulate runtime permissions for
1952            // legacy apps.
1953            if (grantPermissions) {
1954                final int callingUid = Binder.getCallingUid();
1955                mPermissionManager.grantRequestedRuntimePermissions(
1956                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1957                        mPermissionCallback);
1958            }
1959
1960            final boolean update = res.removedInfo != null
1961                    && res.removedInfo.removedPackage != null;
1962            final String installerPackageName =
1963                    res.installerPackageName != null
1964                            ? res.installerPackageName
1965                            : res.removedInfo != null
1966                                    ? res.removedInfo.installerPackageName
1967                                    : null;
1968
1969            // If this is the first time we have child packages for a disabled privileged
1970            // app that had no children, we grant requested runtime permissions to the new
1971            // children if the parent on the system image had them already granted.
1972            if (res.pkg.parentPackage != null) {
1973                final int callingUid = Binder.getCallingUid();
1974                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1975                        res.pkg, callingUid, mPermissionCallback);
1976            }
1977
1978            synchronized (mPackages) {
1979                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1980            }
1981
1982            final String packageName = res.pkg.applicationInfo.packageName;
1983
1984            // Determine the set of users who are adding this package for
1985            // the first time vs. those who are seeing an update.
1986            int[] firstUserIds = EMPTY_INT_ARRAY;
1987            int[] firstInstantUserIds = EMPTY_INT_ARRAY;
1988            int[] updateUserIds = EMPTY_INT_ARRAY;
1989            int[] instantUserIds = EMPTY_INT_ARRAY;
1990            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1991            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1992            for (int newUser : res.newUsers) {
1993                final boolean isInstantApp = ps.getInstantApp(newUser);
1994                if (allNewUsers) {
1995                    if (isInstantApp) {
1996                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
1997                    } else {
1998                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
1999                    }
2000                    continue;
2001                }
2002                boolean isNew = true;
2003                for (int origUser : res.origUsers) {
2004                    if (origUser == newUser) {
2005                        isNew = false;
2006                        break;
2007                    }
2008                }
2009                if (isNew) {
2010                    if (isInstantApp) {
2011                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2012                    } else {
2013                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2014                    }
2015                } else {
2016                    if (isInstantApp) {
2017                        instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser);
2018                    } else {
2019                        updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser);
2020                    }
2021                }
2022            }
2023
2024            // Send installed broadcasts if the package is not a static shared lib.
2025            if (res.pkg.staticSharedLibName == null) {
2026                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2027
2028                // Send added for users that see the package for the first time
2029                // sendPackageAddedForNewUsers also deals with system apps
2030                int appId = UserHandle.getAppId(res.uid);
2031                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2032                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2033                        virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds);
2034
2035                // Send added for users that don't see the package for the first time
2036                Bundle extras = new Bundle(1);
2037                extras.putInt(Intent.EXTRA_UID, res.uid);
2038                if (update) {
2039                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2040                }
2041                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2042                        extras, 0 /*flags*/,
2043                        null /*targetPackage*/, null /*finishedReceiver*/,
2044                        updateUserIds, instantUserIds);
2045                if (installerPackageName != null) {
2046                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2047                            extras, 0 /*flags*/,
2048                            installerPackageName, null /*finishedReceiver*/,
2049                            updateUserIds, instantUserIds);
2050                }
2051
2052                // Send replaced for users that don't see the package for the first time
2053                if (update) {
2054                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2055                            packageName, extras, 0 /*flags*/,
2056                            null /*targetPackage*/, null /*finishedReceiver*/,
2057                            updateUserIds, instantUserIds);
2058                    if (installerPackageName != null) {
2059                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2060                                extras, 0 /*flags*/,
2061                                installerPackageName, null /*finishedReceiver*/,
2062                                updateUserIds, instantUserIds);
2063                    }
2064                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2065                            null /*package*/, null /*extras*/, 0 /*flags*/,
2066                            packageName /*targetPackage*/,
2067                            null /*finishedReceiver*/, updateUserIds, instantUserIds);
2068                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2069                    // First-install and we did a restore, so we're responsible for the
2070                    // first-launch broadcast.
2071                    if (DEBUG_BACKUP) {
2072                        Slog.i(TAG, "Post-restore of " + packageName
2073                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds));
2074                    }
2075                    sendFirstLaunchBroadcast(packageName, installerPackage,
2076                            firstUserIds, firstInstantUserIds);
2077                }
2078
2079                // Send broadcast package appeared if forward locked/external for all users
2080                // treat asec-hosted packages like removable media on upgrade
2081                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2082                    if (DEBUG_INSTALL) {
2083                        Slog.i(TAG, "upgrading pkg " + res.pkg
2084                                + " is ASEC-hosted -> AVAILABLE");
2085                    }
2086                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2087                    ArrayList<String> pkgList = new ArrayList<>(1);
2088                    pkgList.add(packageName);
2089                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2090                }
2091            }
2092
2093            // Work that needs to happen on first install within each user
2094            if (firstUserIds != null && firstUserIds.length > 0) {
2095                synchronized (mPackages) {
2096                    for (int userId : firstUserIds) {
2097                        // If this app is a browser and it's newly-installed for some
2098                        // users, clear any default-browser state in those users. The
2099                        // app's nature doesn't depend on the user, so we can just check
2100                        // its browser nature in any user and generalize.
2101                        if (packageIsBrowser(packageName, userId)) {
2102                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2103                        }
2104
2105                        // We may also need to apply pending (restored) runtime
2106                        // permission grants within these users.
2107                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2108                    }
2109                }
2110            }
2111
2112            if (allNewUsers && !update) {
2113                notifyPackageAdded(packageName);
2114            }
2115
2116            // Log current value of "unknown sources" setting
2117            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2118                    getUnknownSourcesSettings());
2119
2120            // Remove the replaced package's older resources safely now
2121            // We delete after a gc for applications  on sdcard.
2122            if (res.removedInfo != null && res.removedInfo.args != null) {
2123                Runtime.getRuntime().gc();
2124                synchronized (mInstallLock) {
2125                    res.removedInfo.args.doPostDeleteLI(true);
2126                }
2127            } else {
2128                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2129                // and not block here.
2130                VMRuntime.getRuntime().requestConcurrentGC();
2131            }
2132
2133            // Notify DexManager that the package was installed for new users.
2134            // The updated users should already be indexed and the package code paths
2135            // should not change.
2136            // Don't notify the manager for ephemeral apps as they are not expected to
2137            // survive long enough to benefit of background optimizations.
2138            for (int userId : firstUserIds) {
2139                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2140                // There's a race currently where some install events may interleave with an uninstall.
2141                // This can lead to package info being null (b/36642664).
2142                if (info != null) {
2143                    mDexManager.notifyPackageInstalled(info, userId);
2144                }
2145            }
2146        }
2147
2148        // If someone is watching installs - notify them
2149        if (installObserver != null) {
2150            try {
2151                Bundle extras = extrasForInstallResult(res);
2152                installObserver.onPackageInstalled(res.name, res.returnCode,
2153                        res.returnMsg, extras);
2154            } catch (RemoteException e) {
2155                Slog.i(TAG, "Observer no longer exists.");
2156            }
2157        }
2158    }
2159
2160    private StorageEventListener mStorageListener = new StorageEventListener() {
2161        @Override
2162        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2163            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2164                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2165                    final String volumeUuid = vol.getFsUuid();
2166
2167                    // Clean up any users or apps that were removed or recreated
2168                    // while this volume was missing
2169                    sUserManager.reconcileUsers(volumeUuid);
2170                    reconcileApps(volumeUuid);
2171
2172                    // Clean up any install sessions that expired or were
2173                    // cancelled while this volume was missing
2174                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2175
2176                    loadPrivatePackages(vol);
2177
2178                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2179                    unloadPrivatePackages(vol);
2180                }
2181            }
2182        }
2183
2184        @Override
2185        public void onVolumeForgotten(String fsUuid) {
2186            if (TextUtils.isEmpty(fsUuid)) {
2187                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2188                return;
2189            }
2190
2191            // Remove any apps installed on the forgotten volume
2192            synchronized (mPackages) {
2193                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2194                for (PackageSetting ps : packages) {
2195                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2196                    deletePackageVersioned(new VersionedPackage(ps.name,
2197                            PackageManager.VERSION_CODE_HIGHEST),
2198                            new LegacyPackageDeleteObserver(null).getBinder(),
2199                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2200                    // Try very hard to release any references to this package
2201                    // so we don't risk the system server being killed due to
2202                    // open FDs
2203                    AttributeCache.instance().removePackage(ps.name);
2204                }
2205
2206                mSettings.onVolumeForgotten(fsUuid);
2207                mSettings.writeLPr();
2208            }
2209        }
2210    };
2211
2212    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2213        Bundle extras = null;
2214        switch (res.returnCode) {
2215            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2216                extras = new Bundle();
2217                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2218                        res.origPermission);
2219                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2220                        res.origPackage);
2221                break;
2222            }
2223            case PackageManager.INSTALL_SUCCEEDED: {
2224                extras = new Bundle();
2225                extras.putBoolean(Intent.EXTRA_REPLACING,
2226                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2227                break;
2228            }
2229        }
2230        return extras;
2231    }
2232
2233    void scheduleWriteSettingsLocked() {
2234        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2235            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2236        }
2237    }
2238
2239    void scheduleWritePackageListLocked(int userId) {
2240        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2241            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2242            msg.arg1 = userId;
2243            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2244        }
2245    }
2246
2247    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2248        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2249        scheduleWritePackageRestrictionsLocked(userId);
2250    }
2251
2252    void scheduleWritePackageRestrictionsLocked(int userId) {
2253        final int[] userIds = (userId == UserHandle.USER_ALL)
2254                ? sUserManager.getUserIds() : new int[]{userId};
2255        for (int nextUserId : userIds) {
2256            if (!sUserManager.exists(nextUserId)) return;
2257            mDirtyUsers.add(nextUserId);
2258            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2259                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2260            }
2261        }
2262    }
2263
2264    public static PackageManagerService main(Context context, Installer installer,
2265            boolean factoryTest, boolean onlyCore) {
2266        // Self-check for initial settings.
2267        PackageManagerServiceCompilerMapping.checkProperties();
2268
2269        PackageManagerService m = new PackageManagerService(context, installer,
2270                factoryTest, onlyCore);
2271        m.enableSystemUserPackages();
2272        ServiceManager.addService("package", m);
2273        final PackageManagerNative pmn = m.new PackageManagerNative();
2274        ServiceManager.addService("package_native", pmn);
2275        return m;
2276    }
2277
2278    private void enableSystemUserPackages() {
2279        if (!UserManager.isSplitSystemUser()) {
2280            return;
2281        }
2282        // For system user, enable apps based on the following conditions:
2283        // - app is whitelisted or belong to one of these groups:
2284        //   -- system app which has no launcher icons
2285        //   -- system app which has INTERACT_ACROSS_USERS permission
2286        //   -- system IME app
2287        // - app is not in the blacklist
2288        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2289        Set<String> enableApps = new ArraySet<>();
2290        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2291                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2292                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2293        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2294        enableApps.addAll(wlApps);
2295        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2296                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2297        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2298        enableApps.removeAll(blApps);
2299        Log.i(TAG, "Applications installed for system user: " + enableApps);
2300        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2301                UserHandle.SYSTEM);
2302        final int allAppsSize = allAps.size();
2303        synchronized (mPackages) {
2304            for (int i = 0; i < allAppsSize; i++) {
2305                String pName = allAps.get(i);
2306                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2307                // Should not happen, but we shouldn't be failing if it does
2308                if (pkgSetting == null) {
2309                    continue;
2310                }
2311                boolean install = enableApps.contains(pName);
2312                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2313                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2314                            + " for system user");
2315                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2316                }
2317            }
2318            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2319        }
2320    }
2321
2322    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2323        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2324                Context.DISPLAY_SERVICE);
2325        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2326    }
2327
2328    /**
2329     * Requests that files preopted on a secondary system partition be copied to the data partition
2330     * if possible.  Note that the actual copying of the files is accomplished by init for security
2331     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2332     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2333     */
2334    private static void requestCopyPreoptedFiles() {
2335        final int WAIT_TIME_MS = 100;
2336        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2337        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2338            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2339            // We will wait for up to 100 seconds.
2340            final long timeStart = SystemClock.uptimeMillis();
2341            final long timeEnd = timeStart + 100 * 1000;
2342            long timeNow = timeStart;
2343            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2344                try {
2345                    Thread.sleep(WAIT_TIME_MS);
2346                } catch (InterruptedException e) {
2347                    // Do nothing
2348                }
2349                timeNow = SystemClock.uptimeMillis();
2350                if (timeNow > timeEnd) {
2351                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2352                    Slog.wtf(TAG, "cppreopt did not finish!");
2353                    break;
2354                }
2355            }
2356
2357            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2358        }
2359    }
2360
2361    public PackageManagerService(Context context, Installer installer,
2362            boolean factoryTest, boolean onlyCore) {
2363        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2364        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2365        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2366                SystemClock.uptimeMillis());
2367
2368        if (mSdkVersion <= 0) {
2369            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2370        }
2371
2372        mContext = context;
2373
2374        mFactoryTest = factoryTest;
2375        mOnlyCore = onlyCore;
2376        mMetrics = new DisplayMetrics();
2377        mInstaller = installer;
2378
2379        // Create sub-components that provide services / data. Order here is important.
2380        synchronized (mInstallLock) {
2381        synchronized (mPackages) {
2382            // Expose private service for system components to use.
2383            LocalServices.addService(
2384                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2385            sUserManager = new UserManagerService(context, this,
2386                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2387            mPermissionManager = PermissionManagerService.create(context,
2388                    new DefaultPermissionGrantedCallback() {
2389                        @Override
2390                        public void onDefaultRuntimePermissionsGranted(int userId) {
2391                            synchronized(mPackages) {
2392                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2393                            }
2394                        }
2395                    }, mPackages /*externalLock*/);
2396            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2397            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2398        }
2399        }
2400        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2401                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2402        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2403                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2404        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2405                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2406        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2407                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2408        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2409                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2410        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2411                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2412        mSettings.addSharedUserLPw("android.uid.se", SE_UID,
2413                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2414
2415        String separateProcesses = SystemProperties.get("debug.separate_processes");
2416        if (separateProcesses != null && separateProcesses.length() > 0) {
2417            if ("*".equals(separateProcesses)) {
2418                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2419                mSeparateProcesses = null;
2420                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2421            } else {
2422                mDefParseFlags = 0;
2423                mSeparateProcesses = separateProcesses.split(",");
2424                Slog.w(TAG, "Running with debug.separate_processes: "
2425                        + separateProcesses);
2426            }
2427        } else {
2428            mDefParseFlags = 0;
2429            mSeparateProcesses = null;
2430        }
2431
2432        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2433                "*dexopt*");
2434        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2435                installer, mInstallLock);
2436        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2437                dexManagerListener);
2438        mArtManagerService = new ArtManagerService(this, installer, mInstallLock);
2439        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2440
2441        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2442                FgThread.get().getLooper());
2443
2444        getDefaultDisplayMetrics(context, mMetrics);
2445
2446        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2447        SystemConfig systemConfig = SystemConfig.getInstance();
2448        mAvailableFeatures = systemConfig.getAvailableFeatures();
2449        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2450
2451        mProtectedPackages = new ProtectedPackages(mContext);
2452
2453        synchronized (mInstallLock) {
2454        // writer
2455        synchronized (mPackages) {
2456            mHandlerThread = new ServiceThread(TAG,
2457                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2458            mHandlerThread.start();
2459            mHandler = new PackageHandler(mHandlerThread.getLooper());
2460            mProcessLoggingHandler = new ProcessLoggingHandler();
2461            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2462            mInstantAppRegistry = new InstantAppRegistry(this);
2463
2464            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2465            final int builtInLibCount = libConfig.size();
2466            for (int i = 0; i < builtInLibCount; i++) {
2467                String name = libConfig.keyAt(i);
2468                String path = libConfig.valueAt(i);
2469                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2470                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2471            }
2472
2473            SELinuxMMAC.readInstallPolicy();
2474
2475            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2476            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2477            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2478
2479            // Clean up orphaned packages for which the code path doesn't exist
2480            // and they are an update to a system app - caused by bug/32321269
2481            final int packageSettingCount = mSettings.mPackages.size();
2482            for (int i = packageSettingCount - 1; i >= 0; i--) {
2483                PackageSetting ps = mSettings.mPackages.valueAt(i);
2484                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2485                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2486                    mSettings.mPackages.removeAt(i);
2487                    mSettings.enableSystemPackageLPw(ps.name);
2488                }
2489            }
2490
2491            if (mFirstBoot) {
2492                requestCopyPreoptedFiles();
2493            }
2494
2495            String customResolverActivity = Resources.getSystem().getString(
2496                    R.string.config_customResolverActivity);
2497            if (TextUtils.isEmpty(customResolverActivity)) {
2498                customResolverActivity = null;
2499            } else {
2500                mCustomResolverComponentName = ComponentName.unflattenFromString(
2501                        customResolverActivity);
2502            }
2503
2504            long startTime = SystemClock.uptimeMillis();
2505
2506            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2507                    startTime);
2508
2509            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2510            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2511
2512            if (bootClassPath == null) {
2513                Slog.w(TAG, "No BOOTCLASSPATH found!");
2514            }
2515
2516            if (systemServerClassPath == null) {
2517                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2518            }
2519
2520            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2521
2522            final VersionInfo ver = mSettings.getInternalVersion();
2523            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2524            if (mIsUpgrade) {
2525                logCriticalInfo(Log.INFO,
2526                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2527            }
2528
2529            // when upgrading from pre-M, promote system app permissions from install to runtime
2530            mPromoteSystemApps =
2531                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2532
2533            // When upgrading from pre-N, we need to handle package extraction like first boot,
2534            // as there is no profiling data available.
2535            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2536
2537            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2538
2539            // save off the names of pre-existing system packages prior to scanning; we don't
2540            // want to automatically grant runtime permissions for new system apps
2541            if (mPromoteSystemApps) {
2542                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2543                while (pkgSettingIter.hasNext()) {
2544                    PackageSetting ps = pkgSettingIter.next();
2545                    if (isSystemApp(ps)) {
2546                        mExistingSystemPackages.add(ps.name);
2547                    }
2548                }
2549            }
2550
2551            mCacheDir = preparePackageParserCache(mIsUpgrade);
2552
2553            // Set flag to monitor and not change apk file paths when
2554            // scanning install directories.
2555            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2556
2557            if (mIsUpgrade || mFirstBoot) {
2558                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2559            }
2560
2561            // Collect vendor/product overlay packages. (Do this before scanning any apps.)
2562            // For security and version matching reason, only consider
2563            // overlay packages if they reside in the right directory.
2564            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2565                    mDefParseFlags
2566                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2567                    scanFlags
2568                    | SCAN_AS_SYSTEM
2569                    | SCAN_AS_VENDOR,
2570                    0);
2571            scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR),
2572                    mDefParseFlags
2573                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2574                    scanFlags
2575                    | SCAN_AS_SYSTEM
2576                    | SCAN_AS_PRODUCT,
2577                    0);
2578
2579            mParallelPackageParserCallback.findStaticOverlayPackages();
2580
2581            // Find base frameworks (resource packages without code).
2582            scanDirTracedLI(frameworkDir,
2583                    mDefParseFlags
2584                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2585                    scanFlags
2586                    | SCAN_NO_DEX
2587                    | SCAN_AS_SYSTEM
2588                    | SCAN_AS_PRIVILEGED,
2589                    0);
2590
2591            // Collected privileged system packages.
2592            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2593            scanDirTracedLI(privilegedAppDir,
2594                    mDefParseFlags
2595                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2596                    scanFlags
2597                    | SCAN_AS_SYSTEM
2598                    | SCAN_AS_PRIVILEGED,
2599                    0);
2600
2601            // Collect ordinary system packages.
2602            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2603            scanDirTracedLI(systemAppDir,
2604                    mDefParseFlags
2605                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2606                    scanFlags
2607                    | SCAN_AS_SYSTEM,
2608                    0);
2609
2610            // Collected privileged vendor packages.
2611            File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
2612            try {
2613                privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
2614            } catch (IOException e) {
2615                // failed to look up canonical path, continue with original one
2616            }
2617            scanDirTracedLI(privilegedVendorAppDir,
2618                    mDefParseFlags
2619                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2620                    scanFlags
2621                    | SCAN_AS_SYSTEM
2622                    | SCAN_AS_VENDOR
2623                    | SCAN_AS_PRIVILEGED,
2624                    0);
2625
2626            // Collect ordinary vendor packages.
2627            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2628            try {
2629                vendorAppDir = vendorAppDir.getCanonicalFile();
2630            } catch (IOException e) {
2631                // failed to look up canonical path, continue with original one
2632            }
2633            scanDirTracedLI(vendorAppDir,
2634                    mDefParseFlags
2635                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2636                    scanFlags
2637                    | SCAN_AS_SYSTEM
2638                    | SCAN_AS_VENDOR,
2639                    0);
2640
2641            // Collect all OEM packages.
2642            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2643            scanDirTracedLI(oemAppDir,
2644                    mDefParseFlags
2645                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2646                    scanFlags
2647                    | SCAN_AS_SYSTEM
2648                    | SCAN_AS_OEM,
2649                    0);
2650
2651            // Collected privileged product packages.
2652            File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
2653            try {
2654                privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile();
2655            } catch (IOException e) {
2656                // failed to look up canonical path, continue with original one
2657            }
2658            scanDirTracedLI(privilegedProductAppDir,
2659                    mDefParseFlags
2660                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2661                    scanFlags
2662                    | SCAN_AS_SYSTEM
2663                    | SCAN_AS_PRODUCT
2664                    | SCAN_AS_PRIVILEGED,
2665                    0);
2666
2667            // Collect ordinary product packages.
2668            File productAppDir = new File(Environment.getProductDirectory(), "app");
2669            try {
2670                productAppDir = productAppDir.getCanonicalFile();
2671            } catch (IOException e) {
2672                // failed to look up canonical path, continue with original one
2673            }
2674            scanDirTracedLI(productAppDir,
2675                    mDefParseFlags
2676                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2677                    scanFlags
2678                    | SCAN_AS_SYSTEM
2679                    | SCAN_AS_PRODUCT,
2680                    0);
2681
2682            // Prune any system packages that no longer exist.
2683            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2684            // Stub packages must either be replaced with full versions in the /data
2685            // partition or be disabled.
2686            final List<String> stubSystemApps = new ArrayList<>();
2687            if (!mOnlyCore) {
2688                // do this first before mucking with mPackages for the "expecting better" case
2689                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2690                while (pkgIterator.hasNext()) {
2691                    final PackageParser.Package pkg = pkgIterator.next();
2692                    if (pkg.isStub) {
2693                        stubSystemApps.add(pkg.packageName);
2694                    }
2695                }
2696
2697                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2698                while (psit.hasNext()) {
2699                    PackageSetting ps = psit.next();
2700
2701                    /*
2702                     * If this is not a system app, it can't be a
2703                     * disable system app.
2704                     */
2705                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2706                        continue;
2707                    }
2708
2709                    /*
2710                     * If the package is scanned, it's not erased.
2711                     */
2712                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2713                    if (scannedPkg != null) {
2714                        /*
2715                         * If the system app is both scanned and in the
2716                         * disabled packages list, then it must have been
2717                         * added via OTA. Remove it from the currently
2718                         * scanned package so the previously user-installed
2719                         * application can be scanned.
2720                         */
2721                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2722                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2723                                    + ps.name + "; removing system app.  Last known codePath="
2724                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2725                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2726                                    + scannedPkg.getLongVersionCode());
2727                            removePackageLI(scannedPkg, true);
2728                            mExpectingBetter.put(ps.name, ps.codePath);
2729                        }
2730
2731                        continue;
2732                    }
2733
2734                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2735                        psit.remove();
2736                        logCriticalInfo(Log.WARN, "System package " + ps.name
2737                                + " no longer exists; it's data will be wiped");
2738                        // Actual deletion of code and data will be handled by later
2739                        // reconciliation step
2740                    } else {
2741                        // we still have a disabled system package, but, it still might have
2742                        // been removed. check the code path still exists and check there's
2743                        // still a package. the latter can happen if an OTA keeps the same
2744                        // code path, but, changes the package name.
2745                        final PackageSetting disabledPs =
2746                                mSettings.getDisabledSystemPkgLPr(ps.name);
2747                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2748                                || disabledPs.pkg == null) {
2749if (REFACTOR_DEBUG) {
2750Slog.e("TODD",
2751        "Possibly deleted app: " + ps.dumpState_temp()
2752        + "; path: " + (disabledPs.codePath == null ? "<<NULL>>":disabledPs.codePath)
2753        + "; pkg: " + (disabledPs.pkg==null?"<<NULL>>":disabledPs.pkg.toString()));
2754}
2755                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2756                        }
2757                    }
2758                }
2759            }
2760
2761            //look for any incomplete package installations
2762            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2763            for (int i = 0; i < deletePkgsList.size(); i++) {
2764                // Actual deletion of code and data will be handled by later
2765                // reconciliation step
2766                final String packageName = deletePkgsList.get(i).name;
2767                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2768                synchronized (mPackages) {
2769                    mSettings.removePackageLPw(packageName);
2770                }
2771            }
2772
2773            //delete tmp files
2774            deleteTempPackageFiles();
2775
2776            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2777
2778            // Remove any shared userIDs that have no associated packages
2779            mSettings.pruneSharedUsersLPw();
2780            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2781            final int systemPackagesCount = mPackages.size();
2782            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2783                    + " ms, packageCount: " + systemPackagesCount
2784                    + " , timePerPackage: "
2785                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2786                    + " , cached: " + cachedSystemApps);
2787            if (mIsUpgrade && systemPackagesCount > 0) {
2788                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2789                        ((int) systemScanTime) / systemPackagesCount);
2790            }
2791            if (!mOnlyCore) {
2792                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2793                        SystemClock.uptimeMillis());
2794                scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2795
2796                scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags
2797                        | PackageParser.PARSE_FORWARD_LOCK,
2798                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2799
2800                // Remove disable package settings for updated system apps that were
2801                // removed via an OTA. If the update is no longer present, remove the
2802                // app completely. Otherwise, revoke their system privileges.
2803                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2804                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2805                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2806if (REFACTOR_DEBUG) {
2807Slog.e("TODD",
2808        "remove update; name: " + deletedAppName + ", exists? " + (deletedPkg != null));
2809}
2810                    final String msg;
2811                    if (deletedPkg == null) {
2812                        // should have found an update, but, we didn't; remove everything
2813                        msg = "Updated system package " + deletedAppName
2814                                + " no longer exists; removing its data";
2815                        // Actual deletion of code and data will be handled by later
2816                        // reconciliation step
2817                    } else {
2818                        // found an update; revoke system privileges
2819                        msg = "Updated system package + " + deletedAppName
2820                                + " no longer exists; revoking system privileges";
2821
2822                        // Don't do anything if a stub is removed from the system image. If
2823                        // we were to remove the uncompressed version from the /data partition,
2824                        // this is where it'd be done.
2825
2826                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2827                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2828                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2829                    }
2830                    logCriticalInfo(Log.WARN, msg);
2831                }
2832
2833                /*
2834                 * Make sure all system apps that we expected to appear on
2835                 * the userdata partition actually showed up. If they never
2836                 * appeared, crawl back and revive the system version.
2837                 */
2838                for (int i = 0; i < mExpectingBetter.size(); i++) {
2839                    final String packageName = mExpectingBetter.keyAt(i);
2840                    if (!mPackages.containsKey(packageName)) {
2841                        final File scanFile = mExpectingBetter.valueAt(i);
2842
2843                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2844                                + " but never showed up; reverting to system");
2845
2846                        final @ParseFlags int reparseFlags;
2847                        final @ScanFlags int rescanFlags;
2848                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2849                            reparseFlags =
2850                                    mDefParseFlags |
2851                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2852                            rescanFlags =
2853                                    scanFlags
2854                                    | SCAN_AS_SYSTEM
2855                                    | SCAN_AS_PRIVILEGED;
2856                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2857                            reparseFlags =
2858                                    mDefParseFlags |
2859                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2860                            rescanFlags =
2861                                    scanFlags
2862                                    | SCAN_AS_SYSTEM;
2863                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)) {
2864                            reparseFlags =
2865                                    mDefParseFlags |
2866                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2867                            rescanFlags =
2868                                    scanFlags
2869                                    | SCAN_AS_SYSTEM
2870                                    | SCAN_AS_VENDOR
2871                                    | SCAN_AS_PRIVILEGED;
2872                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2873                            reparseFlags =
2874                                    mDefParseFlags |
2875                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2876                            rescanFlags =
2877                                    scanFlags
2878                                    | SCAN_AS_SYSTEM
2879                                    | SCAN_AS_VENDOR;
2880                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2881                            reparseFlags =
2882                                    mDefParseFlags |
2883                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2884                            rescanFlags =
2885                                    scanFlags
2886                                    | SCAN_AS_SYSTEM
2887                                    | SCAN_AS_OEM;
2888                        } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) {
2889                            reparseFlags =
2890                                    mDefParseFlags |
2891                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2892                            rescanFlags =
2893                                    scanFlags
2894                                    | SCAN_AS_SYSTEM
2895                                    | SCAN_AS_PRODUCT
2896                                    | SCAN_AS_PRIVILEGED;
2897                        } else if (FileUtils.contains(productAppDir, scanFile)) {
2898                            reparseFlags =
2899                                    mDefParseFlags |
2900                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2901                            rescanFlags =
2902                                    scanFlags
2903                                    | SCAN_AS_SYSTEM
2904                                    | SCAN_AS_PRODUCT;
2905                        } else {
2906                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2907                            continue;
2908                        }
2909
2910                        mSettings.enableSystemPackageLPw(packageName);
2911
2912                        try {
2913                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2914                        } catch (PackageManagerException e) {
2915                            Slog.e(TAG, "Failed to parse original system package: "
2916                                    + e.getMessage());
2917                        }
2918                    }
2919                }
2920
2921                // Uncompress and install any stubbed system applications.
2922                // This must be done last to ensure all stubs are replaced or disabled.
2923                decompressSystemApplications(stubSystemApps, scanFlags);
2924
2925                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2926                                - cachedSystemApps;
2927
2928                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2929                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2930                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2931                        + " ms, packageCount: " + dataPackagesCount
2932                        + " , timePerPackage: "
2933                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2934                        + " , cached: " + cachedNonSystemApps);
2935                if (mIsUpgrade && dataPackagesCount > 0) {
2936                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2937                            ((int) dataScanTime) / dataPackagesCount);
2938                }
2939            }
2940            mExpectingBetter.clear();
2941
2942            // Resolve the storage manager.
2943            mStorageManagerPackage = getStorageManagerPackageName();
2944
2945            // Resolve protected action filters. Only the setup wizard is allowed to
2946            // have a high priority filter for these actions.
2947            mSetupWizardPackage = getSetupWizardPackageName();
2948            if (mProtectedFilters.size() > 0) {
2949                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2950                    Slog.i(TAG, "No setup wizard;"
2951                        + " All protected intents capped to priority 0");
2952                }
2953                for (ActivityIntentInfo filter : mProtectedFilters) {
2954                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2955                        if (DEBUG_FILTERS) {
2956                            Slog.i(TAG, "Found setup wizard;"
2957                                + " allow priority " + filter.getPriority() + ";"
2958                                + " package: " + filter.activity.info.packageName
2959                                + " activity: " + filter.activity.className
2960                                + " priority: " + filter.getPriority());
2961                        }
2962                        // skip setup wizard; allow it to keep the high priority filter
2963                        continue;
2964                    }
2965                    if (DEBUG_FILTERS) {
2966                        Slog.i(TAG, "Protected action; cap priority to 0;"
2967                                + " package: " + filter.activity.info.packageName
2968                                + " activity: " + filter.activity.className
2969                                + " origPrio: " + filter.getPriority());
2970                    }
2971                    filter.setPriority(0);
2972                }
2973            }
2974            mDeferProtectedFilters = false;
2975            mProtectedFilters.clear();
2976
2977            // Now that we know all of the shared libraries, update all clients to have
2978            // the correct library paths.
2979            updateAllSharedLibrariesLPw(null);
2980
2981            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2982                // NOTE: We ignore potential failures here during a system scan (like
2983                // the rest of the commands above) because there's precious little we
2984                // can do about it. A settings error is reported, though.
2985                final List<String> changedAbiCodePath =
2986                        adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2987                if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
2988                    for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
2989                        final String codePathString = changedAbiCodePath.get(i);
2990                        try {
2991                            mInstaller.rmdex(codePathString,
2992                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
2993                        } catch (InstallerException ignored) {
2994                        }
2995                    }
2996                }
2997            }
2998
2999            // Now that we know all the packages we are keeping,
3000            // read and update their last usage times.
3001            mPackageUsage.read(mPackages);
3002            mCompilerStats.read();
3003
3004            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
3005                    SystemClock.uptimeMillis());
3006            Slog.i(TAG, "Time to scan packages: "
3007                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
3008                    + " seconds");
3009
3010            // If the platform SDK has changed since the last time we booted,
3011            // we need to re-grant app permission to catch any new ones that
3012            // appear.  This is really a hack, and means that apps can in some
3013            // cases get permissions that the user didn't initially explicitly
3014            // allow...  it would be nice to have some better way to handle
3015            // this situation.
3016            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
3017            if (sdkUpdated) {
3018                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
3019                        + mSdkVersion + "; regranting permissions for internal storage");
3020            }
3021            mPermissionManager.updateAllPermissions(
3022                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
3023                    mPermissionCallback);
3024            ver.sdkVersion = mSdkVersion;
3025
3026            // If this is the first boot or an update from pre-M, and it is a normal
3027            // boot, then we need to initialize the default preferred apps across
3028            // all defined users.
3029            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
3030                for (UserInfo user : sUserManager.getUsers(true)) {
3031                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
3032                    applyFactoryDefaultBrowserLPw(user.id);
3033                    primeDomainVerificationsLPw(user.id);
3034                }
3035            }
3036
3037            // Prepare storage for system user really early during boot,
3038            // since core system apps like SettingsProvider and SystemUI
3039            // can't wait for user to start
3040            final int storageFlags;
3041            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3042                storageFlags = StorageManager.FLAG_STORAGE_DE;
3043            } else {
3044                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
3045            }
3046            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
3047                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
3048                    true /* onlyCoreApps */);
3049            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
3050                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
3051                        Trace.TRACE_TAG_PACKAGE_MANAGER);
3052                traceLog.traceBegin("AppDataFixup");
3053                try {
3054                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
3055                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3056                } catch (InstallerException e) {
3057                    Slog.w(TAG, "Trouble fixing GIDs", e);
3058                }
3059                traceLog.traceEnd();
3060
3061                traceLog.traceBegin("AppDataPrepare");
3062                if (deferPackages == null || deferPackages.isEmpty()) {
3063                    return;
3064                }
3065                int count = 0;
3066                for (String pkgName : deferPackages) {
3067                    PackageParser.Package pkg = null;
3068                    synchronized (mPackages) {
3069                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
3070                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
3071                            pkg = ps.pkg;
3072                        }
3073                    }
3074                    if (pkg != null) {
3075                        synchronized (mInstallLock) {
3076                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
3077                                    true /* maybeMigrateAppData */);
3078                        }
3079                        count++;
3080                    }
3081                }
3082                traceLog.traceEnd();
3083                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3084            }, "prepareAppData");
3085
3086            // If this is first boot after an OTA, and a normal boot, then
3087            // we need to clear code cache directories.
3088            // Note that we do *not* clear the application profiles. These remain valid
3089            // across OTAs and are used to drive profile verification (post OTA) and
3090            // profile compilation (without waiting to collect a fresh set of profiles).
3091            if (mIsUpgrade && !onlyCore) {
3092                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3093                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3094                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3095                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3096                        // No apps are running this early, so no need to freeze
3097                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3098                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3099                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3100                    }
3101                }
3102                ver.fingerprint = Build.FINGERPRINT;
3103            }
3104
3105            checkDefaultBrowser();
3106
3107            // clear only after permissions and other defaults have been updated
3108            mExistingSystemPackages.clear();
3109            mPromoteSystemApps = false;
3110
3111            // All the changes are done during package scanning.
3112            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3113
3114            // can downgrade to reader
3115            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3116            mSettings.writeLPr();
3117            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3118            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3119                    SystemClock.uptimeMillis());
3120
3121            if (!mOnlyCore) {
3122                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3123                mRequiredInstallerPackage = getRequiredInstallerLPr();
3124                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3125                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3126                if (mIntentFilterVerifierComponent != null) {
3127                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3128                            mIntentFilterVerifierComponent);
3129                } else {
3130                    mIntentFilterVerifier = null;
3131                }
3132                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3133                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3134                        SharedLibraryInfo.VERSION_UNDEFINED);
3135                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3136                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3137                        SharedLibraryInfo.VERSION_UNDEFINED);
3138            } else {
3139                mRequiredVerifierPackage = null;
3140                mRequiredInstallerPackage = null;
3141                mRequiredUninstallerPackage = null;
3142                mIntentFilterVerifierComponent = null;
3143                mIntentFilterVerifier = null;
3144                mServicesSystemSharedLibraryPackageName = null;
3145                mSharedSystemSharedLibraryPackageName = null;
3146            }
3147
3148            mInstallerService = new PackageInstallerService(context, this);
3149            final Pair<ComponentName, String> instantAppResolverComponent =
3150                    getInstantAppResolverLPr();
3151            if (instantAppResolverComponent != null) {
3152                if (DEBUG_EPHEMERAL) {
3153                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3154                }
3155                mInstantAppResolverConnection = new EphemeralResolverConnection(
3156                        mContext, instantAppResolverComponent.first,
3157                        instantAppResolverComponent.second);
3158                mInstantAppResolverSettingsComponent =
3159                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3160            } else {
3161                mInstantAppResolverConnection = null;
3162                mInstantAppResolverSettingsComponent = null;
3163            }
3164            updateInstantAppInstallerLocked(null);
3165
3166            // Read and update the usage of dex files.
3167            // Do this at the end of PM init so that all the packages have their
3168            // data directory reconciled.
3169            // At this point we know the code paths of the packages, so we can validate
3170            // the disk file and build the internal cache.
3171            // The usage file is expected to be small so loading and verifying it
3172            // should take a fairly small time compare to the other activities (e.g. package
3173            // scanning).
3174            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3175            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3176            for (int userId : currentUserIds) {
3177                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3178            }
3179            mDexManager.load(userPackages);
3180            if (mIsUpgrade) {
3181                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3182                        (int) (SystemClock.uptimeMillis() - startTime));
3183            }
3184        } // synchronized (mPackages)
3185        } // synchronized (mInstallLock)
3186
3187        // Now after opening every single application zip, make sure they
3188        // are all flushed.  Not really needed, but keeps things nice and
3189        // tidy.
3190        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3191        Runtime.getRuntime().gc();
3192        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3193
3194        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3195        FallbackCategoryProvider.loadFallbacks();
3196        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3197
3198        // The initial scanning above does many calls into installd while
3199        // holding the mPackages lock, but we're mostly interested in yelling
3200        // once we have a booted system.
3201        mInstaller.setWarnIfHeld(mPackages);
3202
3203        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3204    }
3205
3206    /**
3207     * Uncompress and install stub applications.
3208     * <p>In order to save space on the system partition, some applications are shipped in a
3209     * compressed form. In addition the compressed bits for the full application, the
3210     * system image contains a tiny stub comprised of only the Android manifest.
3211     * <p>During the first boot, attempt to uncompress and install the full application. If
3212     * the application can't be installed for any reason, disable the stub and prevent
3213     * uncompressing the full application during future boots.
3214     * <p>In order to forcefully attempt an installation of a full application, go to app
3215     * settings and enable the application.
3216     */
3217    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3218        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3219            final String pkgName = stubSystemApps.get(i);
3220            // skip if the system package is already disabled
3221            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3222                stubSystemApps.remove(i);
3223                continue;
3224            }
3225            // skip if the package isn't installed (?!); this should never happen
3226            final PackageParser.Package pkg = mPackages.get(pkgName);
3227            if (pkg == null) {
3228                stubSystemApps.remove(i);
3229                continue;
3230            }
3231            // skip if the package has been disabled by the user
3232            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3233            if (ps != null) {
3234                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3235                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3236                    stubSystemApps.remove(i);
3237                    continue;
3238                }
3239            }
3240
3241            if (DEBUG_COMPRESSION) {
3242                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3243            }
3244
3245            // uncompress the binary to its eventual destination on /data
3246            final File scanFile = decompressPackage(pkg);
3247            if (scanFile == null) {
3248                continue;
3249            }
3250
3251            // install the package to replace the stub on /system
3252            try {
3253                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3254                removePackageLI(pkg, true /*chatty*/);
3255                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3256                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3257                        UserHandle.USER_SYSTEM, "android");
3258                stubSystemApps.remove(i);
3259                continue;
3260            } catch (PackageManagerException e) {
3261                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3262            }
3263
3264            // any failed attempt to install the package will be cleaned up later
3265        }
3266
3267        // disable any stub still left; these failed to install the full application
3268        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3269            final String pkgName = stubSystemApps.get(i);
3270            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3271            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3272                    UserHandle.USER_SYSTEM, "android");
3273            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3274        }
3275    }
3276
3277    /**
3278     * Decompresses the given package on the system image onto
3279     * the /data partition.
3280     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3281     */
3282    private File decompressPackage(PackageParser.Package pkg) {
3283        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3284        if (compressedFiles == null || compressedFiles.length == 0) {
3285            if (DEBUG_COMPRESSION) {
3286                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3287            }
3288            return null;
3289        }
3290        final File dstCodePath =
3291                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3292        int ret = PackageManager.INSTALL_SUCCEEDED;
3293        try {
3294            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3295            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3296            for (File srcFile : compressedFiles) {
3297                final String srcFileName = srcFile.getName();
3298                final String dstFileName = srcFileName.substring(
3299                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3300                final File dstFile = new File(dstCodePath, dstFileName);
3301                ret = decompressFile(srcFile, dstFile);
3302                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3303                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3304                            + "; pkg: " + pkg.packageName
3305                            + ", file: " + dstFileName);
3306                    break;
3307                }
3308            }
3309        } catch (ErrnoException e) {
3310            logCriticalInfo(Log.ERROR, "Failed to decompress"
3311                    + "; pkg: " + pkg.packageName
3312                    + ", err: " + e.errno);
3313        }
3314        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3315            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3316            NativeLibraryHelper.Handle handle = null;
3317            try {
3318                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3319                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3320                        null /*abiOverride*/);
3321            } catch (IOException e) {
3322                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3323                        + "; pkg: " + pkg.packageName);
3324                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3325            } finally {
3326                IoUtils.closeQuietly(handle);
3327            }
3328        }
3329        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3330            if (dstCodePath == null || !dstCodePath.exists()) {
3331                return null;
3332            }
3333            removeCodePathLI(dstCodePath);
3334            return null;
3335        }
3336
3337        return dstCodePath;
3338    }
3339
3340    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3341        // we're only interested in updating the installer appliction when 1) it's not
3342        // already set or 2) the modified package is the installer
3343        if (mInstantAppInstallerActivity != null
3344                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3345                        .equals(modifiedPackage)) {
3346            return;
3347        }
3348        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3349    }
3350
3351    private static File preparePackageParserCache(boolean isUpgrade) {
3352        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3353            return null;
3354        }
3355
3356        // Disable package parsing on eng builds to allow for faster incremental development.
3357        if (Build.IS_ENG) {
3358            return null;
3359        }
3360
3361        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3362            Slog.i(TAG, "Disabling package parser cache due to system property.");
3363            return null;
3364        }
3365
3366        // The base directory for the package parser cache lives under /data/system/.
3367        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3368                "package_cache");
3369        if (cacheBaseDir == null) {
3370            return null;
3371        }
3372
3373        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3374        // This also serves to "GC" unused entries when the package cache version changes (which
3375        // can only happen during upgrades).
3376        if (isUpgrade) {
3377            FileUtils.deleteContents(cacheBaseDir);
3378        }
3379
3380
3381        // Return the versioned package cache directory. This is something like
3382        // "/data/system/package_cache/1"
3383        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3384
3385        // The following is a workaround to aid development on non-numbered userdebug
3386        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3387        // the system partition is newer.
3388        //
3389        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3390        // that starts with "eng." to signify that this is an engineering build and not
3391        // destined for release.
3392        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3393            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3394
3395            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3396            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3397            // in general and should not be used for production changes. In this specific case,
3398            // we know that they will work.
3399            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3400            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3401                FileUtils.deleteContents(cacheBaseDir);
3402                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3403            }
3404        }
3405
3406        return cacheDir;
3407    }
3408
3409    @Override
3410    public boolean isFirstBoot() {
3411        // allow instant applications
3412        return mFirstBoot;
3413    }
3414
3415    @Override
3416    public boolean isOnlyCoreApps() {
3417        // allow instant applications
3418        return mOnlyCore;
3419    }
3420
3421    @Override
3422    public boolean isUpgrade() {
3423        // allow instant applications
3424        // The system property allows testing ota flow when upgraded to the same image.
3425        return mIsUpgrade || SystemProperties.getBoolean(
3426                "persist.pm.mock-upgrade", false /* default */);
3427    }
3428
3429    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3430        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3431
3432        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3433                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3434                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3435        if (matches.size() == 1) {
3436            return matches.get(0).getComponentInfo().packageName;
3437        } else if (matches.size() == 0) {
3438            Log.e(TAG, "There should probably be a verifier, but, none were found");
3439            return null;
3440        }
3441        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3442    }
3443
3444    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3445        synchronized (mPackages) {
3446            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3447            if (libraryEntry == null) {
3448                throw new IllegalStateException("Missing required shared library:" + name);
3449            }
3450            return libraryEntry.apk;
3451        }
3452    }
3453
3454    private @NonNull String getRequiredInstallerLPr() {
3455        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3456        intent.addCategory(Intent.CATEGORY_DEFAULT);
3457        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3458
3459        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3460                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3461                UserHandle.USER_SYSTEM);
3462        if (matches.size() == 1) {
3463            ResolveInfo resolveInfo = matches.get(0);
3464            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3465                throw new RuntimeException("The installer must be a privileged app");
3466            }
3467            return matches.get(0).getComponentInfo().packageName;
3468        } else {
3469            throw new RuntimeException("There must be exactly one installer; found " + matches);
3470        }
3471    }
3472
3473    private @NonNull String getRequiredUninstallerLPr() {
3474        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3475        intent.addCategory(Intent.CATEGORY_DEFAULT);
3476        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3477
3478        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3479                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3480                UserHandle.USER_SYSTEM);
3481        if (resolveInfo == null ||
3482                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3483            throw new RuntimeException("There must be exactly one uninstaller; found "
3484                    + resolveInfo);
3485        }
3486        return resolveInfo.getComponentInfo().packageName;
3487    }
3488
3489    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3490        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3491
3492        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3493                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3494                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3495        ResolveInfo best = null;
3496        final int N = matches.size();
3497        for (int i = 0; i < N; i++) {
3498            final ResolveInfo cur = matches.get(i);
3499            final String packageName = cur.getComponentInfo().packageName;
3500            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3501                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3502                continue;
3503            }
3504
3505            if (best == null || cur.priority > best.priority) {
3506                best = cur;
3507            }
3508        }
3509
3510        if (best != null) {
3511            return best.getComponentInfo().getComponentName();
3512        }
3513        Slog.w(TAG, "Intent filter verifier not found");
3514        return null;
3515    }
3516
3517    @Override
3518    public @Nullable ComponentName getInstantAppResolverComponent() {
3519        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3520            return null;
3521        }
3522        synchronized (mPackages) {
3523            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3524            if (instantAppResolver == null) {
3525                return null;
3526            }
3527            return instantAppResolver.first;
3528        }
3529    }
3530
3531    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3532        final String[] packageArray =
3533                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3534        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3535            if (DEBUG_EPHEMERAL) {
3536                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3537            }
3538            return null;
3539        }
3540
3541        final int callingUid = Binder.getCallingUid();
3542        final int resolveFlags =
3543                MATCH_DIRECT_BOOT_AWARE
3544                | MATCH_DIRECT_BOOT_UNAWARE
3545                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3546        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3547        final Intent resolverIntent = new Intent(actionName);
3548        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3549                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3550        // temporarily look for the old action
3551        if (resolvers.size() == 0) {
3552            if (DEBUG_EPHEMERAL) {
3553                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3554            }
3555            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3556            resolverIntent.setAction(actionName);
3557            resolvers = queryIntentServicesInternal(resolverIntent, null,
3558                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3559        }
3560        final int N = resolvers.size();
3561        if (N == 0) {
3562            if (DEBUG_EPHEMERAL) {
3563                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3564            }
3565            return null;
3566        }
3567
3568        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3569        for (int i = 0; i < N; i++) {
3570            final ResolveInfo info = resolvers.get(i);
3571
3572            if (info.serviceInfo == null) {
3573                continue;
3574            }
3575
3576            final String packageName = info.serviceInfo.packageName;
3577            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3578                if (DEBUG_EPHEMERAL) {
3579                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3580                            + " pkg: " + packageName + ", info:" + info);
3581                }
3582                continue;
3583            }
3584
3585            if (DEBUG_EPHEMERAL) {
3586                Slog.v(TAG, "Ephemeral resolver found;"
3587                        + " pkg: " + packageName + ", info:" + info);
3588            }
3589            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3590        }
3591        if (DEBUG_EPHEMERAL) {
3592            Slog.v(TAG, "Ephemeral resolver NOT found");
3593        }
3594        return null;
3595    }
3596
3597    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3598        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3599        intent.addCategory(Intent.CATEGORY_DEFAULT);
3600        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3601
3602        final int resolveFlags =
3603                MATCH_DIRECT_BOOT_AWARE
3604                | MATCH_DIRECT_BOOT_UNAWARE
3605                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3606        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3607                resolveFlags, UserHandle.USER_SYSTEM);
3608        // temporarily look for the old action
3609        if (matches.isEmpty()) {
3610            if (DEBUG_EPHEMERAL) {
3611                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3612            }
3613            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3614            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3615                    resolveFlags, UserHandle.USER_SYSTEM);
3616        }
3617        Iterator<ResolveInfo> iter = matches.iterator();
3618        while (iter.hasNext()) {
3619            final ResolveInfo rInfo = iter.next();
3620            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3621            if (ps != null) {
3622                final PermissionsState permissionsState = ps.getPermissionsState();
3623                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3624                    continue;
3625                }
3626            }
3627            iter.remove();
3628        }
3629        if (matches.size() == 0) {
3630            return null;
3631        } else if (matches.size() == 1) {
3632            return (ActivityInfo) matches.get(0).getComponentInfo();
3633        } else {
3634            throw new RuntimeException(
3635                    "There must be at most one ephemeral installer; found " + matches);
3636        }
3637    }
3638
3639    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3640            @NonNull ComponentName resolver) {
3641        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3642                .addCategory(Intent.CATEGORY_DEFAULT)
3643                .setPackage(resolver.getPackageName());
3644        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3645        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3646                UserHandle.USER_SYSTEM);
3647        // temporarily look for the old action
3648        if (matches.isEmpty()) {
3649            if (DEBUG_EPHEMERAL) {
3650                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3651            }
3652            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3653            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3654                    UserHandle.USER_SYSTEM);
3655        }
3656        if (matches.isEmpty()) {
3657            return null;
3658        }
3659        return matches.get(0).getComponentInfo().getComponentName();
3660    }
3661
3662    private void primeDomainVerificationsLPw(int userId) {
3663        if (DEBUG_DOMAIN_VERIFICATION) {
3664            Slog.d(TAG, "Priming domain verifications in user " + userId);
3665        }
3666
3667        SystemConfig systemConfig = SystemConfig.getInstance();
3668        ArraySet<String> packages = systemConfig.getLinkedApps();
3669
3670        for (String packageName : packages) {
3671            PackageParser.Package pkg = mPackages.get(packageName);
3672            if (pkg != null) {
3673                if (!pkg.isSystem()) {
3674                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3675                    continue;
3676                }
3677
3678                ArraySet<String> domains = null;
3679                for (PackageParser.Activity a : pkg.activities) {
3680                    for (ActivityIntentInfo filter : a.intents) {
3681                        if (hasValidDomains(filter)) {
3682                            if (domains == null) {
3683                                domains = new ArraySet<String>();
3684                            }
3685                            domains.addAll(filter.getHostsList());
3686                        }
3687                    }
3688                }
3689
3690                if (domains != null && domains.size() > 0) {
3691                    if (DEBUG_DOMAIN_VERIFICATION) {
3692                        Slog.v(TAG, "      + " + packageName);
3693                    }
3694                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3695                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3696                    // and then 'always' in the per-user state actually used for intent resolution.
3697                    final IntentFilterVerificationInfo ivi;
3698                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3699                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3700                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3701                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3702                } else {
3703                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3704                            + "' does not handle web links");
3705                }
3706            } else {
3707                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3708            }
3709        }
3710
3711        scheduleWritePackageRestrictionsLocked(userId);
3712        scheduleWriteSettingsLocked();
3713    }
3714
3715    private void applyFactoryDefaultBrowserLPw(int userId) {
3716        // The default browser app's package name is stored in a string resource,
3717        // with a product-specific overlay used for vendor customization.
3718        String browserPkg = mContext.getResources().getString(
3719                com.android.internal.R.string.default_browser);
3720        if (!TextUtils.isEmpty(browserPkg)) {
3721            // non-empty string => required to be a known package
3722            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3723            if (ps == null) {
3724                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3725                browserPkg = null;
3726            } else {
3727                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3728            }
3729        }
3730
3731        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3732        // default.  If there's more than one, just leave everything alone.
3733        if (browserPkg == null) {
3734            calculateDefaultBrowserLPw(userId);
3735        }
3736    }
3737
3738    private void calculateDefaultBrowserLPw(int userId) {
3739        List<String> allBrowsers = resolveAllBrowserApps(userId);
3740        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3741        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3742    }
3743
3744    private List<String> resolveAllBrowserApps(int userId) {
3745        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3746        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3747                PackageManager.MATCH_ALL, userId);
3748
3749        final int count = list.size();
3750        List<String> result = new ArrayList<String>(count);
3751        for (int i=0; i<count; i++) {
3752            ResolveInfo info = list.get(i);
3753            if (info.activityInfo == null
3754                    || !info.handleAllWebDataURI
3755                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3756                    || result.contains(info.activityInfo.packageName)) {
3757                continue;
3758            }
3759            result.add(info.activityInfo.packageName);
3760        }
3761
3762        return result;
3763    }
3764
3765    private boolean packageIsBrowser(String packageName, int userId) {
3766        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3767                PackageManager.MATCH_ALL, userId);
3768        final int N = list.size();
3769        for (int i = 0; i < N; i++) {
3770            ResolveInfo info = list.get(i);
3771            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3772                return true;
3773            }
3774        }
3775        return false;
3776    }
3777
3778    private void checkDefaultBrowser() {
3779        final int myUserId = UserHandle.myUserId();
3780        final String packageName = getDefaultBrowserPackageName(myUserId);
3781        if (packageName != null) {
3782            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3783            if (info == null) {
3784                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3785                synchronized (mPackages) {
3786                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3787                }
3788            }
3789        }
3790    }
3791
3792    @Override
3793    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3794            throws RemoteException {
3795        try {
3796            return super.onTransact(code, data, reply, flags);
3797        } catch (RuntimeException e) {
3798            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3799                Slog.wtf(TAG, "Package Manager Crash", e);
3800            }
3801            throw e;
3802        }
3803    }
3804
3805    static int[] appendInts(int[] cur, int[] add) {
3806        if (add == null) return cur;
3807        if (cur == null) return add;
3808        final int N = add.length;
3809        for (int i=0; i<N; i++) {
3810            cur = appendInt(cur, add[i]);
3811        }
3812        return cur;
3813    }
3814
3815    /**
3816     * Returns whether or not a full application can see an instant application.
3817     * <p>
3818     * Currently, there are three cases in which this can occur:
3819     * <ol>
3820     * <li>The calling application is a "special" process. Special processes
3821     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3822     * <li>The calling application has the permission
3823     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3824     * <li>The calling application is the default launcher on the
3825     *     system partition.</li>
3826     * </ol>
3827     */
3828    private boolean canViewInstantApps(int callingUid, int userId) {
3829        if (callingUid < Process.FIRST_APPLICATION_UID) {
3830            return true;
3831        }
3832        if (mContext.checkCallingOrSelfPermission(
3833                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3834            return true;
3835        }
3836        if (mContext.checkCallingOrSelfPermission(
3837                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3838            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3839            if (homeComponent != null
3840                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3841                return true;
3842            }
3843        }
3844        return false;
3845    }
3846
3847    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3848        if (!sUserManager.exists(userId)) return null;
3849        if (ps == null) {
3850            return null;
3851        }
3852        PackageParser.Package p = ps.pkg;
3853        if (p == null) {
3854            return null;
3855        }
3856        final int callingUid = Binder.getCallingUid();
3857        // Filter out ephemeral app metadata:
3858        //   * The system/shell/root can see metadata for any app
3859        //   * An installed app can see metadata for 1) other installed apps
3860        //     and 2) ephemeral apps that have explicitly interacted with it
3861        //   * Ephemeral apps can only see their own data and exposed installed apps
3862        //   * Holding a signature permission allows seeing instant apps
3863        if (filterAppAccessLPr(ps, callingUid, userId)) {
3864            return null;
3865        }
3866
3867        final PermissionsState permissionsState = ps.getPermissionsState();
3868
3869        // Compute GIDs only if requested
3870        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3871                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3872        // Compute granted permissions only if package has requested permissions
3873        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3874                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3875        final PackageUserState state = ps.readUserState(userId);
3876
3877        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3878                && ps.isSystem()) {
3879            flags |= MATCH_ANY_USER;
3880        }
3881
3882        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3883                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3884
3885        if (packageInfo == null) {
3886            return null;
3887        }
3888
3889        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3890                resolveExternalPackageNameLPr(p);
3891
3892        return packageInfo;
3893    }
3894
3895    @Override
3896    public void checkPackageStartable(String packageName, int userId) {
3897        final int callingUid = Binder.getCallingUid();
3898        if (getInstantAppPackageName(callingUid) != null) {
3899            throw new SecurityException("Instant applications don't have access to this method");
3900        }
3901        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3902        synchronized (mPackages) {
3903            final PackageSetting ps = mSettings.mPackages.get(packageName);
3904            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3905                throw new SecurityException("Package " + packageName + " was not found!");
3906            }
3907
3908            if (!ps.getInstalled(userId)) {
3909                throw new SecurityException(
3910                        "Package " + packageName + " was not installed for user " + userId + "!");
3911            }
3912
3913            if (mSafeMode && !ps.isSystem()) {
3914                throw new SecurityException("Package " + packageName + " not a system app!");
3915            }
3916
3917            if (mFrozenPackages.contains(packageName)) {
3918                throw new SecurityException("Package " + packageName + " is currently frozen!");
3919            }
3920
3921            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3922                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3923            }
3924        }
3925    }
3926
3927    @Override
3928    public boolean isPackageAvailable(String packageName, int userId) {
3929        if (!sUserManager.exists(userId)) return false;
3930        final int callingUid = Binder.getCallingUid();
3931        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3932                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3933        synchronized (mPackages) {
3934            PackageParser.Package p = mPackages.get(packageName);
3935            if (p != null) {
3936                final PackageSetting ps = (PackageSetting) p.mExtras;
3937                if (filterAppAccessLPr(ps, callingUid, userId)) {
3938                    return false;
3939                }
3940                if (ps != null) {
3941                    final PackageUserState state = ps.readUserState(userId);
3942                    if (state != null) {
3943                        return PackageParser.isAvailable(state);
3944                    }
3945                }
3946            }
3947        }
3948        return false;
3949    }
3950
3951    @Override
3952    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3953        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3954                flags, Binder.getCallingUid(), userId);
3955    }
3956
3957    @Override
3958    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3959            int flags, int userId) {
3960        return getPackageInfoInternal(versionedPackage.getPackageName(),
3961                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
3962    }
3963
3964    /**
3965     * Important: The provided filterCallingUid is used exclusively to filter out packages
3966     * that can be seen based on user state. It's typically the original caller uid prior
3967     * to clearing. Because it can only be provided by trusted code, it's value can be
3968     * trusted and will be used as-is; unlike userId which will be validated by this method.
3969     */
3970    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
3971            int flags, int filterCallingUid, int userId) {
3972        if (!sUserManager.exists(userId)) return null;
3973        flags = updateFlagsForPackage(flags, userId, packageName);
3974        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
3975                false /* requireFullPermission */, false /* checkShell */, "get package info");
3976
3977        // reader
3978        synchronized (mPackages) {
3979            // Normalize package name to handle renamed packages and static libs
3980            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3981
3982            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3983            if (matchFactoryOnly) {
3984                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3985                if (ps != null) {
3986                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3987                        return null;
3988                    }
3989                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3990                        return null;
3991                    }
3992                    return generatePackageInfo(ps, flags, userId);
3993                }
3994            }
3995
3996            PackageParser.Package p = mPackages.get(packageName);
3997            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3998                return null;
3999            }
4000            if (DEBUG_PACKAGE_INFO)
4001                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
4002            if (p != null) {
4003                final PackageSetting ps = (PackageSetting) p.mExtras;
4004                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4005                    return null;
4006                }
4007                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
4008                    return null;
4009                }
4010                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4011            }
4012            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4013                final PackageSetting ps = mSettings.mPackages.get(packageName);
4014                if (ps == null) return null;
4015                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4016                    return null;
4017                }
4018                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4019                    return null;
4020                }
4021                return generatePackageInfo(ps, flags, userId);
4022            }
4023        }
4024        return null;
4025    }
4026
4027    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4028        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4029            return true;
4030        }
4031        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4032            return true;
4033        }
4034        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4035            return true;
4036        }
4037        return false;
4038    }
4039
4040    private boolean isComponentVisibleToInstantApp(
4041            @Nullable ComponentName component, @ComponentType int type) {
4042        if (type == TYPE_ACTIVITY) {
4043            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4044            return activity != null
4045                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4046                    : false;
4047        } else if (type == TYPE_RECEIVER) {
4048            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4049            return activity != null
4050                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4051                    : false;
4052        } else if (type == TYPE_SERVICE) {
4053            final PackageParser.Service service = mServices.mServices.get(component);
4054            return service != null
4055                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4056                    : false;
4057        } else if (type == TYPE_PROVIDER) {
4058            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4059            return provider != null
4060                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4061                    : false;
4062        } else if (type == TYPE_UNKNOWN) {
4063            return isComponentVisibleToInstantApp(component);
4064        }
4065        return false;
4066    }
4067
4068    /**
4069     * Returns whether or not access to the application should be filtered.
4070     * <p>
4071     * Access may be limited based upon whether the calling or target applications
4072     * are instant applications.
4073     *
4074     * @see #canAccessInstantApps(int)
4075     */
4076    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4077            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4078        // if we're in an isolated process, get the real calling UID
4079        if (Process.isIsolated(callingUid)) {
4080            callingUid = mIsolatedOwners.get(callingUid);
4081        }
4082        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4083        final boolean callerIsInstantApp = instantAppPkgName != null;
4084        if (ps == null) {
4085            if (callerIsInstantApp) {
4086                // pretend the application exists, but, needs to be filtered
4087                return true;
4088            }
4089            return false;
4090        }
4091        // if the target and caller are the same application, don't filter
4092        if (isCallerSameApp(ps.name, callingUid)) {
4093            return false;
4094        }
4095        if (callerIsInstantApp) {
4096            // request for a specific component; if it hasn't been explicitly exposed, filter
4097            if (component != null) {
4098                return !isComponentVisibleToInstantApp(component, componentType);
4099            }
4100            // request for application; if no components have been explicitly exposed, filter
4101            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4102        }
4103        if (ps.getInstantApp(userId)) {
4104            // caller can see all components of all instant applications, don't filter
4105            if (canViewInstantApps(callingUid, userId)) {
4106                return false;
4107            }
4108            // request for a specific instant application component, filter
4109            if (component != null) {
4110                return true;
4111            }
4112            // request for an instant application; if the caller hasn't been granted access, filter
4113            return !mInstantAppRegistry.isInstantAccessGranted(
4114                    userId, UserHandle.getAppId(callingUid), ps.appId);
4115        }
4116        return false;
4117    }
4118
4119    /**
4120     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4121     */
4122    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4123        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4124    }
4125
4126    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4127            int flags) {
4128        // Callers can access only the libs they depend on, otherwise they need to explicitly
4129        // ask for the shared libraries given the caller is allowed to access all static libs.
4130        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4131            // System/shell/root get to see all static libs
4132            final int appId = UserHandle.getAppId(uid);
4133            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4134                    || appId == Process.ROOT_UID) {
4135                return false;
4136            }
4137        }
4138
4139        // No package means no static lib as it is always on internal storage
4140        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4141            return false;
4142        }
4143
4144        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4145                ps.pkg.staticSharedLibVersion);
4146        if (libEntry == null) {
4147            return false;
4148        }
4149
4150        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4151        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4152        if (uidPackageNames == null) {
4153            return true;
4154        }
4155
4156        for (String uidPackageName : uidPackageNames) {
4157            if (ps.name.equals(uidPackageName)) {
4158                return false;
4159            }
4160            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4161            if (uidPs != null) {
4162                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4163                        libEntry.info.getName());
4164                if (index < 0) {
4165                    continue;
4166                }
4167                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4168                    return false;
4169                }
4170            }
4171        }
4172        return true;
4173    }
4174
4175    @Override
4176    public String[] currentToCanonicalPackageNames(String[] names) {
4177        final int callingUid = Binder.getCallingUid();
4178        if (getInstantAppPackageName(callingUid) != null) {
4179            return names;
4180        }
4181        final String[] out = new String[names.length];
4182        // reader
4183        synchronized (mPackages) {
4184            final int callingUserId = UserHandle.getUserId(callingUid);
4185            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4186            for (int i=names.length-1; i>=0; i--) {
4187                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4188                boolean translateName = false;
4189                if (ps != null && ps.realName != null) {
4190                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4191                    translateName = !targetIsInstantApp
4192                            || canViewInstantApps
4193                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4194                                    UserHandle.getAppId(callingUid), ps.appId);
4195                }
4196                out[i] = translateName ? ps.realName : names[i];
4197            }
4198        }
4199        return out;
4200    }
4201
4202    @Override
4203    public String[] canonicalToCurrentPackageNames(String[] names) {
4204        final int callingUid = Binder.getCallingUid();
4205        if (getInstantAppPackageName(callingUid) != null) {
4206            return names;
4207        }
4208        final String[] out = new String[names.length];
4209        // reader
4210        synchronized (mPackages) {
4211            final int callingUserId = UserHandle.getUserId(callingUid);
4212            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4213            for (int i=names.length-1; i>=0; i--) {
4214                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4215                boolean translateName = false;
4216                if (cur != null) {
4217                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4218                    final boolean targetIsInstantApp =
4219                            ps != null && ps.getInstantApp(callingUserId);
4220                    translateName = !targetIsInstantApp
4221                            || canViewInstantApps
4222                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4223                                    UserHandle.getAppId(callingUid), ps.appId);
4224                }
4225                out[i] = translateName ? cur : names[i];
4226            }
4227        }
4228        return out;
4229    }
4230
4231    @Override
4232    public int getPackageUid(String packageName, int flags, int userId) {
4233        if (!sUserManager.exists(userId)) return -1;
4234        final int callingUid = Binder.getCallingUid();
4235        flags = updateFlagsForPackage(flags, userId, packageName);
4236        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4237                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4238
4239        // reader
4240        synchronized (mPackages) {
4241            final PackageParser.Package p = mPackages.get(packageName);
4242            if (p != null && p.isMatch(flags)) {
4243                PackageSetting ps = (PackageSetting) p.mExtras;
4244                if (filterAppAccessLPr(ps, callingUid, userId)) {
4245                    return -1;
4246                }
4247                return UserHandle.getUid(userId, p.applicationInfo.uid);
4248            }
4249            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4250                final PackageSetting ps = mSettings.mPackages.get(packageName);
4251                if (ps != null && ps.isMatch(flags)
4252                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4253                    return UserHandle.getUid(userId, ps.appId);
4254                }
4255            }
4256        }
4257
4258        return -1;
4259    }
4260
4261    @Override
4262    public int[] getPackageGids(String packageName, int flags, int userId) {
4263        if (!sUserManager.exists(userId)) return null;
4264        final int callingUid = Binder.getCallingUid();
4265        flags = updateFlagsForPackage(flags, userId, packageName);
4266        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4267                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4268
4269        // reader
4270        synchronized (mPackages) {
4271            final PackageParser.Package p = mPackages.get(packageName);
4272            if (p != null && p.isMatch(flags)) {
4273                PackageSetting ps = (PackageSetting) p.mExtras;
4274                if (filterAppAccessLPr(ps, callingUid, userId)) {
4275                    return null;
4276                }
4277                // TODO: Shouldn't this be checking for package installed state for userId and
4278                // return null?
4279                return ps.getPermissionsState().computeGids(userId);
4280            }
4281            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4282                final PackageSetting ps = mSettings.mPackages.get(packageName);
4283                if (ps != null && ps.isMatch(flags)
4284                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4285                    return ps.getPermissionsState().computeGids(userId);
4286                }
4287            }
4288        }
4289
4290        return null;
4291    }
4292
4293    @Override
4294    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4295        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4296    }
4297
4298    @Override
4299    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4300            int flags) {
4301        final List<PermissionInfo> permissionList =
4302                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4303        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4304    }
4305
4306    @Override
4307    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4308        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4309    }
4310
4311    @Override
4312    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4313        final List<PermissionGroupInfo> permissionList =
4314                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4315        return (permissionList == null)
4316                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4317    }
4318
4319    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4320            int filterCallingUid, int userId) {
4321        if (!sUserManager.exists(userId)) return null;
4322        PackageSetting ps = mSettings.mPackages.get(packageName);
4323        if (ps != null) {
4324            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4325                return null;
4326            }
4327            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4328                return null;
4329            }
4330            if (ps.pkg == null) {
4331                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4332                if (pInfo != null) {
4333                    return pInfo.applicationInfo;
4334                }
4335                return null;
4336            }
4337            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4338                    ps.readUserState(userId), userId);
4339            if (ai != null) {
4340                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4341            }
4342            return ai;
4343        }
4344        return null;
4345    }
4346
4347    @Override
4348    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4349        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4350    }
4351
4352    /**
4353     * Important: The provided filterCallingUid is used exclusively to filter out applications
4354     * that can be seen based on user state. It's typically the original caller uid prior
4355     * to clearing. Because it can only be provided by trusted code, it's value can be
4356     * trusted and will be used as-is; unlike userId which will be validated by this method.
4357     */
4358    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4359            int filterCallingUid, int userId) {
4360        if (!sUserManager.exists(userId)) return null;
4361        flags = updateFlagsForApplication(flags, userId, packageName);
4362        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4363                false /* requireFullPermission */, false /* checkShell */, "get application info");
4364
4365        // writer
4366        synchronized (mPackages) {
4367            // Normalize package name to handle renamed packages and static libs
4368            packageName = resolveInternalPackageNameLPr(packageName,
4369                    PackageManager.VERSION_CODE_HIGHEST);
4370
4371            PackageParser.Package p = mPackages.get(packageName);
4372            if (DEBUG_PACKAGE_INFO) Log.v(
4373                    TAG, "getApplicationInfo " + packageName
4374                    + ": " + p);
4375            if (p != null) {
4376                PackageSetting ps = mSettings.mPackages.get(packageName);
4377                if (ps == null) return null;
4378                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4379                    return null;
4380                }
4381                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4382                    return null;
4383                }
4384                // Note: isEnabledLP() does not apply here - always return info
4385                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4386                        p, flags, ps.readUserState(userId), userId);
4387                if (ai != null) {
4388                    ai.packageName = resolveExternalPackageNameLPr(p);
4389                }
4390                return ai;
4391            }
4392            if ("android".equals(packageName)||"system".equals(packageName)) {
4393                return mAndroidApplication;
4394            }
4395            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4396                // Already generates the external package name
4397                return generateApplicationInfoFromSettingsLPw(packageName,
4398                        flags, filterCallingUid, userId);
4399            }
4400        }
4401        return null;
4402    }
4403
4404    private String normalizePackageNameLPr(String packageName) {
4405        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4406        return normalizedPackageName != null ? normalizedPackageName : packageName;
4407    }
4408
4409    @Override
4410    public void deletePreloadsFileCache() {
4411        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4412            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4413        }
4414        File dir = Environment.getDataPreloadsFileCacheDirectory();
4415        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4416        FileUtils.deleteContents(dir);
4417    }
4418
4419    @Override
4420    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4421            final int storageFlags, final IPackageDataObserver observer) {
4422        mContext.enforceCallingOrSelfPermission(
4423                android.Manifest.permission.CLEAR_APP_CACHE, null);
4424        mHandler.post(() -> {
4425            boolean success = false;
4426            try {
4427                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4428                success = true;
4429            } catch (IOException e) {
4430                Slog.w(TAG, e);
4431            }
4432            if (observer != null) {
4433                try {
4434                    observer.onRemoveCompleted(null, success);
4435                } catch (RemoteException e) {
4436                    Slog.w(TAG, e);
4437                }
4438            }
4439        });
4440    }
4441
4442    @Override
4443    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4444            final int storageFlags, final IntentSender pi) {
4445        mContext.enforceCallingOrSelfPermission(
4446                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4447        mHandler.post(() -> {
4448            boolean success = false;
4449            try {
4450                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4451                success = true;
4452            } catch (IOException e) {
4453                Slog.w(TAG, e);
4454            }
4455            if (pi != null) {
4456                try {
4457                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4458                } catch (SendIntentException e) {
4459                    Slog.w(TAG, e);
4460                }
4461            }
4462        });
4463    }
4464
4465    /**
4466     * Blocking call to clear various types of cached data across the system
4467     * until the requested bytes are available.
4468     */
4469    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4470        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4471        final File file = storage.findPathForUuid(volumeUuid);
4472        if (file.getUsableSpace() >= bytes) return;
4473
4474        if (ENABLE_FREE_CACHE_V2) {
4475            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4476                    volumeUuid);
4477            final boolean aggressive = (storageFlags
4478                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4479            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4480
4481            // 1. Pre-flight to determine if we have any chance to succeed
4482            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4483            if (internalVolume && (aggressive || SystemProperties
4484                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4485                deletePreloadsFileCache();
4486                if (file.getUsableSpace() >= bytes) return;
4487            }
4488
4489            // 3. Consider parsed APK data (aggressive only)
4490            if (internalVolume && aggressive) {
4491                FileUtils.deleteContents(mCacheDir);
4492                if (file.getUsableSpace() >= bytes) return;
4493            }
4494
4495            // 4. Consider cached app data (above quotas)
4496            try {
4497                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4498                        Installer.FLAG_FREE_CACHE_V2);
4499            } catch (InstallerException ignored) {
4500            }
4501            if (file.getUsableSpace() >= bytes) return;
4502
4503            // 5. Consider shared libraries with refcount=0 and age>min cache period
4504            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4505                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4506                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4507                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4508                return;
4509            }
4510
4511            // 6. Consider dexopt output (aggressive only)
4512            // TODO: Implement
4513
4514            // 7. Consider installed instant apps unused longer than min cache period
4515            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4516                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4517                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4518                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4519                return;
4520            }
4521
4522            // 8. Consider cached app data (below quotas)
4523            try {
4524                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4525                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4526            } catch (InstallerException ignored) {
4527            }
4528            if (file.getUsableSpace() >= bytes) return;
4529
4530            // 9. Consider DropBox entries
4531            // TODO: Implement
4532
4533            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4534            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4535                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4536                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4537                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4538                return;
4539            }
4540        } else {
4541            try {
4542                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4543            } catch (InstallerException ignored) {
4544            }
4545            if (file.getUsableSpace() >= bytes) return;
4546        }
4547
4548        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4549    }
4550
4551    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4552            throws IOException {
4553        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4554        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4555
4556        List<VersionedPackage> packagesToDelete = null;
4557        final long now = System.currentTimeMillis();
4558
4559        synchronized (mPackages) {
4560            final int[] allUsers = sUserManager.getUserIds();
4561            final int libCount = mSharedLibraries.size();
4562            for (int i = 0; i < libCount; i++) {
4563                final LongSparseArray<SharedLibraryEntry> versionedLib
4564                        = mSharedLibraries.valueAt(i);
4565                if (versionedLib == null) {
4566                    continue;
4567                }
4568                final int versionCount = versionedLib.size();
4569                for (int j = 0; j < versionCount; j++) {
4570                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4571                    // Skip packages that are not static shared libs.
4572                    if (!libInfo.isStatic()) {
4573                        break;
4574                    }
4575                    // Important: We skip static shared libs used for some user since
4576                    // in such a case we need to keep the APK on the device. The check for
4577                    // a lib being used for any user is performed by the uninstall call.
4578                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4579                    // Resolve the package name - we use synthetic package names internally
4580                    final String internalPackageName = resolveInternalPackageNameLPr(
4581                            declaringPackage.getPackageName(),
4582                            declaringPackage.getLongVersionCode());
4583                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4584                    // Skip unused static shared libs cached less than the min period
4585                    // to prevent pruning a lib needed by a subsequently installed package.
4586                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4587                        continue;
4588                    }
4589                    if (packagesToDelete == null) {
4590                        packagesToDelete = new ArrayList<>();
4591                    }
4592                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4593                            declaringPackage.getLongVersionCode()));
4594                }
4595            }
4596        }
4597
4598        if (packagesToDelete != null) {
4599            final int packageCount = packagesToDelete.size();
4600            for (int i = 0; i < packageCount; i++) {
4601                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4602                // Delete the package synchronously (will fail of the lib used for any user).
4603                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4604                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4605                                == PackageManager.DELETE_SUCCEEDED) {
4606                    if (volume.getUsableSpace() >= neededSpace) {
4607                        return true;
4608                    }
4609                }
4610            }
4611        }
4612
4613        return false;
4614    }
4615
4616    /**
4617     * Update given flags based on encryption status of current user.
4618     */
4619    private int updateFlags(int flags, int userId) {
4620        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4621                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4622            // Caller expressed an explicit opinion about what encryption
4623            // aware/unaware components they want to see, so fall through and
4624            // give them what they want
4625        } else {
4626            // Caller expressed no opinion, so match based on user state
4627            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4628                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4629            } else {
4630                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4631            }
4632        }
4633        return flags;
4634    }
4635
4636    private UserManagerInternal getUserManagerInternal() {
4637        if (mUserManagerInternal == null) {
4638            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4639        }
4640        return mUserManagerInternal;
4641    }
4642
4643    private ActivityManagerInternal getActivityManagerInternal() {
4644        if (mActivityManagerInternal == null) {
4645            mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
4646        }
4647        return mActivityManagerInternal;
4648    }
4649
4650
4651    private DeviceIdleController.LocalService getDeviceIdleController() {
4652        if (mDeviceIdleController == null) {
4653            mDeviceIdleController =
4654                    LocalServices.getService(DeviceIdleController.LocalService.class);
4655        }
4656        return mDeviceIdleController;
4657    }
4658
4659    /**
4660     * Update given flags when being used to request {@link PackageInfo}.
4661     */
4662    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4663        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4664        boolean triaged = true;
4665        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4666                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4667            // Caller is asking for component details, so they'd better be
4668            // asking for specific encryption matching behavior, or be triaged
4669            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4670                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4671                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4672                triaged = false;
4673            }
4674        }
4675        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4676                | PackageManager.MATCH_SYSTEM_ONLY
4677                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4678            triaged = false;
4679        }
4680        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4681            mPermissionManager.enforceCrossUserPermission(
4682                    Binder.getCallingUid(), userId, false, false,
4683                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4684                    + Debug.getCallers(5));
4685        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4686                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4687            // If the caller wants all packages and has a restricted profile associated with it,
4688            // then match all users. This is to make sure that launchers that need to access work
4689            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4690            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4691            flags |= PackageManager.MATCH_ANY_USER;
4692        }
4693        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4694            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4695                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4696        }
4697        return updateFlags(flags, userId);
4698    }
4699
4700    /**
4701     * Update given flags when being used to request {@link ApplicationInfo}.
4702     */
4703    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4704        return updateFlagsForPackage(flags, userId, cookie);
4705    }
4706
4707    /**
4708     * Update given flags when being used to request {@link ComponentInfo}.
4709     */
4710    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4711        if (cookie instanceof Intent) {
4712            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4713                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4714            }
4715        }
4716
4717        boolean triaged = true;
4718        // Caller is asking for component details, so they'd better be
4719        // asking for specific encryption matching behavior, or be triaged
4720        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4721                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4722                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4723            triaged = false;
4724        }
4725        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4726            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4727                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4728        }
4729
4730        return updateFlags(flags, userId);
4731    }
4732
4733    /**
4734     * Update given intent when being used to request {@link ResolveInfo}.
4735     */
4736    private Intent updateIntentForResolve(Intent intent) {
4737        if (intent.getSelector() != null) {
4738            intent = intent.getSelector();
4739        }
4740        if (DEBUG_PREFERRED) {
4741            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4742        }
4743        return intent;
4744    }
4745
4746    /**
4747     * Update given flags when being used to request {@link ResolveInfo}.
4748     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4749     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4750     * flag set. However, this flag is only honoured in three circumstances:
4751     * <ul>
4752     * <li>when called from a system process</li>
4753     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4754     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4755     * action and a {@code android.intent.category.BROWSABLE} category</li>
4756     * </ul>
4757     */
4758    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4759        return updateFlagsForResolve(flags, userId, intent, callingUid,
4760                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4761    }
4762    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4763            boolean wantInstantApps) {
4764        return updateFlagsForResolve(flags, userId, intent, callingUid,
4765                wantInstantApps, false /*onlyExposedExplicitly*/);
4766    }
4767    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4768            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4769        // Safe mode means we shouldn't match any third-party components
4770        if (mSafeMode) {
4771            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4772        }
4773        if (getInstantAppPackageName(callingUid) != null) {
4774            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4775            if (onlyExposedExplicitly) {
4776                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4777            }
4778            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4779            flags |= PackageManager.MATCH_INSTANT;
4780        } else {
4781            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4782            final boolean allowMatchInstant =
4783                    (wantInstantApps
4784                            && Intent.ACTION_VIEW.equals(intent.getAction())
4785                            && hasWebURI(intent))
4786                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4787            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4788                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4789            if (!allowMatchInstant) {
4790                flags &= ~PackageManager.MATCH_INSTANT;
4791            }
4792        }
4793        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4794    }
4795
4796    @Override
4797    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4798        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4799    }
4800
4801    /**
4802     * Important: The provided filterCallingUid is used exclusively to filter out activities
4803     * that can be seen based on user state. It's typically the original caller uid prior
4804     * to clearing. Because it can only be provided by trusted code, it's value can be
4805     * trusted and will be used as-is; unlike userId which will be validated by this method.
4806     */
4807    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4808            int filterCallingUid, int userId) {
4809        if (!sUserManager.exists(userId)) return null;
4810        flags = updateFlagsForComponent(flags, userId, component);
4811
4812        if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) {
4813            mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4814                    false /* requireFullPermission */, false /* checkShell */, "get activity info");
4815        }
4816
4817        synchronized (mPackages) {
4818            PackageParser.Activity a = mActivities.mActivities.get(component);
4819
4820            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4821            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4822                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4823                if (ps == null) return null;
4824                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4825                    return null;
4826                }
4827                return PackageParser.generateActivityInfo(
4828                        a, flags, ps.readUserState(userId), userId);
4829            }
4830            if (mResolveComponentName.equals(component)) {
4831                return PackageParser.generateActivityInfo(
4832                        mResolveActivity, flags, new PackageUserState(), userId);
4833            }
4834        }
4835        return null;
4836    }
4837
4838    private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) {
4839        if (!getActivityManagerInternal().isCallerRecents(callingUid)) {
4840            return false;
4841        }
4842        final long token = Binder.clearCallingIdentity();
4843        try {
4844            final int callingUserId = UserHandle.getUserId(callingUid);
4845            if (ActivityManager.getCurrentUser() != callingUserId) {
4846                return false;
4847            }
4848            return sUserManager.isSameProfileGroup(callingUserId, targetUserId);
4849        } finally {
4850            Binder.restoreCallingIdentity(token);
4851        }
4852    }
4853
4854    @Override
4855    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4856            String resolvedType) {
4857        synchronized (mPackages) {
4858            if (component.equals(mResolveComponentName)) {
4859                // The resolver supports EVERYTHING!
4860                return true;
4861            }
4862            final int callingUid = Binder.getCallingUid();
4863            final int callingUserId = UserHandle.getUserId(callingUid);
4864            PackageParser.Activity a = mActivities.mActivities.get(component);
4865            if (a == null) {
4866                return false;
4867            }
4868            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4869            if (ps == null) {
4870                return false;
4871            }
4872            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4873                return false;
4874            }
4875            for (int i=0; i<a.intents.size(); i++) {
4876                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4877                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4878                    return true;
4879                }
4880            }
4881            return false;
4882        }
4883    }
4884
4885    @Override
4886    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4887        if (!sUserManager.exists(userId)) return null;
4888        final int callingUid = Binder.getCallingUid();
4889        flags = updateFlagsForComponent(flags, userId, component);
4890        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4891                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4892        synchronized (mPackages) {
4893            PackageParser.Activity a = mReceivers.mActivities.get(component);
4894            if (DEBUG_PACKAGE_INFO) Log.v(
4895                TAG, "getReceiverInfo " + component + ": " + a);
4896            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4897                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4898                if (ps == null) return null;
4899                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4900                    return null;
4901                }
4902                return PackageParser.generateActivityInfo(
4903                        a, flags, ps.readUserState(userId), userId);
4904            }
4905        }
4906        return null;
4907    }
4908
4909    @Override
4910    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4911            int flags, int userId) {
4912        if (!sUserManager.exists(userId)) return null;
4913        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4914        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4915            return null;
4916        }
4917
4918        flags = updateFlagsForPackage(flags, userId, null);
4919
4920        final boolean canSeeStaticLibraries =
4921                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4922                        == PERMISSION_GRANTED
4923                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4924                        == PERMISSION_GRANTED
4925                || canRequestPackageInstallsInternal(packageName,
4926                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4927                        false  /* throwIfPermNotDeclared*/)
4928                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4929                        == PERMISSION_GRANTED;
4930
4931        synchronized (mPackages) {
4932            List<SharedLibraryInfo> result = null;
4933
4934            final int libCount = mSharedLibraries.size();
4935            for (int i = 0; i < libCount; i++) {
4936                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4937                if (versionedLib == null) {
4938                    continue;
4939                }
4940
4941                final int versionCount = versionedLib.size();
4942                for (int j = 0; j < versionCount; j++) {
4943                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4944                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4945                        break;
4946                    }
4947                    final long identity = Binder.clearCallingIdentity();
4948                    try {
4949                        PackageInfo packageInfo = getPackageInfoVersioned(
4950                                libInfo.getDeclaringPackage(), flags
4951                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4952                        if (packageInfo == null) {
4953                            continue;
4954                        }
4955                    } finally {
4956                        Binder.restoreCallingIdentity(identity);
4957                    }
4958
4959                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4960                            libInfo.getLongVersion(), libInfo.getType(),
4961                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4962                            flags, userId));
4963
4964                    if (result == null) {
4965                        result = new ArrayList<>();
4966                    }
4967                    result.add(resLibInfo);
4968                }
4969            }
4970
4971            return result != null ? new ParceledListSlice<>(result) : null;
4972        }
4973    }
4974
4975    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4976            SharedLibraryInfo libInfo, int flags, int userId) {
4977        List<VersionedPackage> versionedPackages = null;
4978        final int packageCount = mSettings.mPackages.size();
4979        for (int i = 0; i < packageCount; i++) {
4980            PackageSetting ps = mSettings.mPackages.valueAt(i);
4981
4982            if (ps == null) {
4983                continue;
4984            }
4985
4986            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4987                continue;
4988            }
4989
4990            final String libName = libInfo.getName();
4991            if (libInfo.isStatic()) {
4992                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4993                if (libIdx < 0) {
4994                    continue;
4995                }
4996                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
4997                    continue;
4998                }
4999                if (versionedPackages == null) {
5000                    versionedPackages = new ArrayList<>();
5001                }
5002                // If the dependent is a static shared lib, use the public package name
5003                String dependentPackageName = ps.name;
5004                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5005                    dependentPackageName = ps.pkg.manifestPackageName;
5006                }
5007                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5008            } else if (ps.pkg != null) {
5009                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5010                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5011                    if (versionedPackages == null) {
5012                        versionedPackages = new ArrayList<>();
5013                    }
5014                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5015                }
5016            }
5017        }
5018
5019        return versionedPackages;
5020    }
5021
5022    @Override
5023    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5024        if (!sUserManager.exists(userId)) return null;
5025        final int callingUid = Binder.getCallingUid();
5026        flags = updateFlagsForComponent(flags, userId, component);
5027        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5028                false /* requireFullPermission */, false /* checkShell */, "get service info");
5029        synchronized (mPackages) {
5030            PackageParser.Service s = mServices.mServices.get(component);
5031            if (DEBUG_PACKAGE_INFO) Log.v(
5032                TAG, "getServiceInfo " + component + ": " + s);
5033            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5034                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5035                if (ps == null) return null;
5036                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5037                    return null;
5038                }
5039                return PackageParser.generateServiceInfo(
5040                        s, flags, ps.readUserState(userId), userId);
5041            }
5042        }
5043        return null;
5044    }
5045
5046    @Override
5047    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5048        if (!sUserManager.exists(userId)) return null;
5049        final int callingUid = Binder.getCallingUid();
5050        flags = updateFlagsForComponent(flags, userId, component);
5051        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5052                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5053        synchronized (mPackages) {
5054            PackageParser.Provider p = mProviders.mProviders.get(component);
5055            if (DEBUG_PACKAGE_INFO) Log.v(
5056                TAG, "getProviderInfo " + component + ": " + p);
5057            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5058                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5059                if (ps == null) return null;
5060                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5061                    return null;
5062                }
5063                return PackageParser.generateProviderInfo(
5064                        p, flags, ps.readUserState(userId), userId);
5065            }
5066        }
5067        return null;
5068    }
5069
5070    @Override
5071    public String[] getSystemSharedLibraryNames() {
5072        // allow instant applications
5073        synchronized (mPackages) {
5074            Set<String> libs = null;
5075            final int libCount = mSharedLibraries.size();
5076            for (int i = 0; i < libCount; i++) {
5077                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5078                if (versionedLib == null) {
5079                    continue;
5080                }
5081                final int versionCount = versionedLib.size();
5082                for (int j = 0; j < versionCount; j++) {
5083                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5084                    if (!libEntry.info.isStatic()) {
5085                        if (libs == null) {
5086                            libs = new ArraySet<>();
5087                        }
5088                        libs.add(libEntry.info.getName());
5089                        break;
5090                    }
5091                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5092                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5093                            UserHandle.getUserId(Binder.getCallingUid()),
5094                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5095                        if (libs == null) {
5096                            libs = new ArraySet<>();
5097                        }
5098                        libs.add(libEntry.info.getName());
5099                        break;
5100                    }
5101                }
5102            }
5103
5104            if (libs != null) {
5105                String[] libsArray = new String[libs.size()];
5106                libs.toArray(libsArray);
5107                return libsArray;
5108            }
5109
5110            return null;
5111        }
5112    }
5113
5114    @Override
5115    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5116        // allow instant applications
5117        synchronized (mPackages) {
5118            return mServicesSystemSharedLibraryPackageName;
5119        }
5120    }
5121
5122    @Override
5123    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5124        // allow instant applications
5125        synchronized (mPackages) {
5126            return mSharedSystemSharedLibraryPackageName;
5127        }
5128    }
5129
5130    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5131        for (int i = userList.length - 1; i >= 0; --i) {
5132            final int userId = userList[i];
5133            // don't add instant app to the list of updates
5134            if (pkgSetting.getInstantApp(userId)) {
5135                continue;
5136            }
5137            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5138            if (changedPackages == null) {
5139                changedPackages = new SparseArray<>();
5140                mChangedPackages.put(userId, changedPackages);
5141            }
5142            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5143            if (sequenceNumbers == null) {
5144                sequenceNumbers = new HashMap<>();
5145                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5146            }
5147            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5148            if (sequenceNumber != null) {
5149                changedPackages.remove(sequenceNumber);
5150            }
5151            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5152            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5153        }
5154        mChangedPackagesSequenceNumber++;
5155    }
5156
5157    @Override
5158    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5159        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5160            return null;
5161        }
5162        synchronized (mPackages) {
5163            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5164                return null;
5165            }
5166            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5167            if (changedPackages == null) {
5168                return null;
5169            }
5170            final List<String> packageNames =
5171                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5172            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5173                final String packageName = changedPackages.get(i);
5174                if (packageName != null) {
5175                    packageNames.add(packageName);
5176                }
5177            }
5178            return packageNames.isEmpty()
5179                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5180        }
5181    }
5182
5183    @Override
5184    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5185        // allow instant applications
5186        ArrayList<FeatureInfo> res;
5187        synchronized (mAvailableFeatures) {
5188            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5189            res.addAll(mAvailableFeatures.values());
5190        }
5191        final FeatureInfo fi = new FeatureInfo();
5192        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5193                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5194        res.add(fi);
5195
5196        return new ParceledListSlice<>(res);
5197    }
5198
5199    @Override
5200    public boolean hasSystemFeature(String name, int version) {
5201        // allow instant applications
5202        synchronized (mAvailableFeatures) {
5203            final FeatureInfo feat = mAvailableFeatures.get(name);
5204            if (feat == null) {
5205                return false;
5206            } else {
5207                return feat.version >= version;
5208            }
5209        }
5210    }
5211
5212    @Override
5213    public int checkPermission(String permName, String pkgName, int userId) {
5214        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5215    }
5216
5217    @Override
5218    public int checkUidPermission(String permName, int uid) {
5219        return mPermissionManager.checkUidPermission(permName, uid, getCallingUid());
5220    }
5221
5222    @Override
5223    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5224        if (UserHandle.getCallingUserId() != userId) {
5225            mContext.enforceCallingPermission(
5226                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5227                    "isPermissionRevokedByPolicy for user " + userId);
5228        }
5229
5230        if (checkPermission(permission, packageName, userId)
5231                == PackageManager.PERMISSION_GRANTED) {
5232            return false;
5233        }
5234
5235        final int callingUid = Binder.getCallingUid();
5236        if (getInstantAppPackageName(callingUid) != null) {
5237            if (!isCallerSameApp(packageName, callingUid)) {
5238                return false;
5239            }
5240        } else {
5241            if (isInstantApp(packageName, userId)) {
5242                return false;
5243            }
5244        }
5245
5246        final long identity = Binder.clearCallingIdentity();
5247        try {
5248            final int flags = getPermissionFlags(permission, packageName, userId);
5249            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5250        } finally {
5251            Binder.restoreCallingIdentity(identity);
5252        }
5253    }
5254
5255    @Override
5256    public String getPermissionControllerPackageName() {
5257        synchronized (mPackages) {
5258            return mRequiredInstallerPackage;
5259        }
5260    }
5261
5262    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5263        return mPermissionManager.addDynamicPermission(
5264                info, async, getCallingUid(), new PermissionCallback() {
5265                    @Override
5266                    public void onPermissionChanged() {
5267                        if (!async) {
5268                            mSettings.writeLPr();
5269                        } else {
5270                            scheduleWriteSettingsLocked();
5271                        }
5272                    }
5273                });
5274    }
5275
5276    @Override
5277    public boolean addPermission(PermissionInfo info) {
5278        synchronized (mPackages) {
5279            return addDynamicPermission(info, false);
5280        }
5281    }
5282
5283    @Override
5284    public boolean addPermissionAsync(PermissionInfo info) {
5285        synchronized (mPackages) {
5286            return addDynamicPermission(info, true);
5287        }
5288    }
5289
5290    @Override
5291    public void removePermission(String permName) {
5292        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5293    }
5294
5295    @Override
5296    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5297        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5298                getCallingUid(), userId, mPermissionCallback);
5299    }
5300
5301    @Override
5302    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5303        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5304                getCallingUid(), userId, mPermissionCallback);
5305    }
5306
5307    @Override
5308    public void resetRuntimePermissions() {
5309        mContext.enforceCallingOrSelfPermission(
5310                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5311                "revokeRuntimePermission");
5312
5313        int callingUid = Binder.getCallingUid();
5314        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5315            mContext.enforceCallingOrSelfPermission(
5316                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5317                    "resetRuntimePermissions");
5318        }
5319
5320        synchronized (mPackages) {
5321            mPermissionManager.updateAllPermissions(
5322                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5323                    mPermissionCallback);
5324            for (int userId : UserManagerService.getInstance().getUserIds()) {
5325                final int packageCount = mPackages.size();
5326                for (int i = 0; i < packageCount; i++) {
5327                    PackageParser.Package pkg = mPackages.valueAt(i);
5328                    if (!(pkg.mExtras instanceof PackageSetting)) {
5329                        continue;
5330                    }
5331                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5332                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5333                }
5334            }
5335        }
5336    }
5337
5338    @Override
5339    public int getPermissionFlags(String permName, String packageName, int userId) {
5340        return mPermissionManager.getPermissionFlags(
5341                permName, packageName, getCallingUid(), userId);
5342    }
5343
5344    @Override
5345    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5346            int flagValues, int userId) {
5347        mPermissionManager.updatePermissionFlags(
5348                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5349                mPermissionCallback);
5350    }
5351
5352    /**
5353     * Update the permission flags for all packages and runtime permissions of a user in order
5354     * to allow device or profile owner to remove POLICY_FIXED.
5355     */
5356    @Override
5357    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5358        synchronized (mPackages) {
5359            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5360                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5361                    mPermissionCallback);
5362            if (changed) {
5363                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5364            }
5365        }
5366    }
5367
5368    @Override
5369    public boolean shouldShowRequestPermissionRationale(String permissionName,
5370            String packageName, int userId) {
5371        if (UserHandle.getCallingUserId() != userId) {
5372            mContext.enforceCallingPermission(
5373                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5374                    "canShowRequestPermissionRationale for user " + userId);
5375        }
5376
5377        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5378        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5379            return false;
5380        }
5381
5382        if (checkPermission(permissionName, packageName, userId)
5383                == PackageManager.PERMISSION_GRANTED) {
5384            return false;
5385        }
5386
5387        final int flags;
5388
5389        final long identity = Binder.clearCallingIdentity();
5390        try {
5391            flags = getPermissionFlags(permissionName,
5392                    packageName, userId);
5393        } finally {
5394            Binder.restoreCallingIdentity(identity);
5395        }
5396
5397        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5398                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5399                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5400
5401        if ((flags & fixedFlags) != 0) {
5402            return false;
5403        }
5404
5405        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5406    }
5407
5408    @Override
5409    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5410        mContext.enforceCallingOrSelfPermission(
5411                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5412                "addOnPermissionsChangeListener");
5413
5414        synchronized (mPackages) {
5415            mOnPermissionChangeListeners.addListenerLocked(listener);
5416        }
5417    }
5418
5419    @Override
5420    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5421        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5422            throw new SecurityException("Instant applications don't have access to this method");
5423        }
5424        synchronized (mPackages) {
5425            mOnPermissionChangeListeners.removeListenerLocked(listener);
5426        }
5427    }
5428
5429    @Override
5430    public boolean isProtectedBroadcast(String actionName) {
5431        // allow instant applications
5432        synchronized (mProtectedBroadcasts) {
5433            if (mProtectedBroadcasts.contains(actionName)) {
5434                return true;
5435            } else if (actionName != null) {
5436                // TODO: remove these terrible hacks
5437                if (actionName.startsWith("android.net.netmon.lingerExpired")
5438                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5439                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5440                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5441                    return true;
5442                }
5443            }
5444        }
5445        return false;
5446    }
5447
5448    @Override
5449    public int checkSignatures(String pkg1, String pkg2) {
5450        synchronized (mPackages) {
5451            final PackageParser.Package p1 = mPackages.get(pkg1);
5452            final PackageParser.Package p2 = mPackages.get(pkg2);
5453            if (p1 == null || p1.mExtras == null
5454                    || p2 == null || p2.mExtras == null) {
5455                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5456            }
5457            final int callingUid = Binder.getCallingUid();
5458            final int callingUserId = UserHandle.getUserId(callingUid);
5459            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5460            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5461            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5462                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5463                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5464            }
5465            return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures);
5466        }
5467    }
5468
5469    @Override
5470    public int checkUidSignatures(int uid1, int uid2) {
5471        final int callingUid = Binder.getCallingUid();
5472        final int callingUserId = UserHandle.getUserId(callingUid);
5473        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5474        // Map to base uids.
5475        uid1 = UserHandle.getAppId(uid1);
5476        uid2 = UserHandle.getAppId(uid2);
5477        // reader
5478        synchronized (mPackages) {
5479            Signature[] s1;
5480            Signature[] s2;
5481            Object obj = mSettings.getUserIdLPr(uid1);
5482            if (obj != null) {
5483                if (obj instanceof SharedUserSetting) {
5484                    if (isCallerInstantApp) {
5485                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5486                    }
5487                    s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5488                } else if (obj instanceof PackageSetting) {
5489                    final PackageSetting ps = (PackageSetting) obj;
5490                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5491                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5492                    }
5493                    s1 = ps.signatures.mSigningDetails.signatures;
5494                } else {
5495                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5496                }
5497            } else {
5498                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5499            }
5500            obj = mSettings.getUserIdLPr(uid2);
5501            if (obj != null) {
5502                if (obj instanceof SharedUserSetting) {
5503                    if (isCallerInstantApp) {
5504                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5505                    }
5506                    s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5507                } else if (obj instanceof PackageSetting) {
5508                    final PackageSetting ps = (PackageSetting) obj;
5509                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5510                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5511                    }
5512                    s2 = ps.signatures.mSigningDetails.signatures;
5513                } else {
5514                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5515                }
5516            } else {
5517                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5518            }
5519            return compareSignatures(s1, s2);
5520        }
5521    }
5522
5523    @Override
5524    public boolean hasSigningCertificate(
5525            String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) {
5526
5527        synchronized (mPackages) {
5528            final PackageParser.Package p = mPackages.get(packageName);
5529            if (p == null || p.mExtras == null) {
5530                return false;
5531            }
5532            final int callingUid = Binder.getCallingUid();
5533            final int callingUserId = UserHandle.getUserId(callingUid);
5534            final PackageSetting ps = (PackageSetting) p.mExtras;
5535            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5536                return false;
5537            }
5538            switch (type) {
5539                case CERT_INPUT_RAW_X509:
5540                    return signingDetailsHasCertificate(certificate, p.mSigningDetails);
5541                case CERT_INPUT_SHA256:
5542                    return signingDetailsHasSha256Certificate(certificate, p.mSigningDetails);
5543                default:
5544                    return false;
5545            }
5546        }
5547    }
5548
5549    @Override
5550    public boolean hasUidSigningCertificate(
5551            int uid, byte[] certificate, @PackageManager.CertificateInputType int type) {
5552        final int callingUid = Binder.getCallingUid();
5553        final int callingUserId = UserHandle.getUserId(callingUid);
5554        // Map to base uids.
5555        uid = UserHandle.getAppId(uid);
5556        // reader
5557        synchronized (mPackages) {
5558            final PackageParser.SigningDetails signingDetails;
5559            final Object obj = mSettings.getUserIdLPr(uid);
5560            if (obj != null) {
5561                if (obj instanceof SharedUserSetting) {
5562                    final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5563                    if (isCallerInstantApp) {
5564                        return false;
5565                    }
5566                    signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails;
5567                } else if (obj instanceof PackageSetting) {
5568                    final PackageSetting ps = (PackageSetting) obj;
5569                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5570                        return false;
5571                    }
5572                    signingDetails = ps.signatures.mSigningDetails;
5573                } else {
5574                    return false;
5575                }
5576            } else {
5577                return false;
5578            }
5579            switch (type) {
5580                case CERT_INPUT_RAW_X509:
5581                    return signingDetailsHasCertificate(certificate, signingDetails);
5582                case CERT_INPUT_SHA256:
5583                    return signingDetailsHasSha256Certificate(certificate, signingDetails);
5584                default:
5585                    return false;
5586            }
5587        }
5588    }
5589
5590    /**
5591     * This method should typically only be used when granting or revoking
5592     * permissions, since the app may immediately restart after this call.
5593     * <p>
5594     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5595     * guard your work against the app being relaunched.
5596     */
5597    private void killUid(int appId, int userId, String reason) {
5598        final long identity = Binder.clearCallingIdentity();
5599        try {
5600            IActivityManager am = ActivityManager.getService();
5601            if (am != null) {
5602                try {
5603                    am.killUid(appId, userId, reason);
5604                } catch (RemoteException e) {
5605                    /* ignore - same process */
5606                }
5607            }
5608        } finally {
5609            Binder.restoreCallingIdentity(identity);
5610        }
5611    }
5612
5613    /**
5614     * If the database version for this type of package (internal storage or
5615     * external storage) is less than the version where package signatures
5616     * were updated, return true.
5617     */
5618    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5619        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5620        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5621    }
5622
5623    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5624        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5625        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5626    }
5627
5628    @Override
5629    public List<String> getAllPackages() {
5630        final int callingUid = Binder.getCallingUid();
5631        final int callingUserId = UserHandle.getUserId(callingUid);
5632        synchronized (mPackages) {
5633            if (canViewInstantApps(callingUid, callingUserId)) {
5634                return new ArrayList<String>(mPackages.keySet());
5635            }
5636            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5637            final List<String> result = new ArrayList<>();
5638            if (instantAppPkgName != null) {
5639                // caller is an instant application; filter unexposed applications
5640                for (PackageParser.Package pkg : mPackages.values()) {
5641                    if (!pkg.visibleToInstantApps) {
5642                        continue;
5643                    }
5644                    result.add(pkg.packageName);
5645                }
5646            } else {
5647                // caller is a normal application; filter instant applications
5648                for (PackageParser.Package pkg : mPackages.values()) {
5649                    final PackageSetting ps =
5650                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5651                    if (ps != null
5652                            && ps.getInstantApp(callingUserId)
5653                            && !mInstantAppRegistry.isInstantAccessGranted(
5654                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5655                        continue;
5656                    }
5657                    result.add(pkg.packageName);
5658                }
5659            }
5660            return result;
5661        }
5662    }
5663
5664    @Override
5665    public String[] getPackagesForUid(int uid) {
5666        final int callingUid = Binder.getCallingUid();
5667        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5668        final int userId = UserHandle.getUserId(uid);
5669        uid = UserHandle.getAppId(uid);
5670        // reader
5671        synchronized (mPackages) {
5672            Object obj = mSettings.getUserIdLPr(uid);
5673            if (obj instanceof SharedUserSetting) {
5674                if (isCallerInstantApp) {
5675                    return null;
5676                }
5677                final SharedUserSetting sus = (SharedUserSetting) obj;
5678                final int N = sus.packages.size();
5679                String[] res = new String[N];
5680                final Iterator<PackageSetting> it = sus.packages.iterator();
5681                int i = 0;
5682                while (it.hasNext()) {
5683                    PackageSetting ps = it.next();
5684                    if (ps.getInstalled(userId)) {
5685                        res[i++] = ps.name;
5686                    } else {
5687                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5688                    }
5689                }
5690                return res;
5691            } else if (obj instanceof PackageSetting) {
5692                final PackageSetting ps = (PackageSetting) obj;
5693                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5694                    return new String[]{ps.name};
5695                }
5696            }
5697        }
5698        return null;
5699    }
5700
5701    @Override
5702    public String getNameForUid(int uid) {
5703        final int callingUid = Binder.getCallingUid();
5704        if (getInstantAppPackageName(callingUid) != null) {
5705            return null;
5706        }
5707        synchronized (mPackages) {
5708            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5709            if (obj instanceof SharedUserSetting) {
5710                final SharedUserSetting sus = (SharedUserSetting) obj;
5711                return sus.name + ":" + sus.userId;
5712            } else if (obj instanceof PackageSetting) {
5713                final PackageSetting ps = (PackageSetting) obj;
5714                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5715                    return null;
5716                }
5717                return ps.name;
5718            }
5719            return null;
5720        }
5721    }
5722
5723    @Override
5724    public String[] getNamesForUids(int[] uids) {
5725        if (uids == null || uids.length == 0) {
5726            return null;
5727        }
5728        final int callingUid = Binder.getCallingUid();
5729        if (getInstantAppPackageName(callingUid) != null) {
5730            return null;
5731        }
5732        final String[] names = new String[uids.length];
5733        synchronized (mPackages) {
5734            for (int i = uids.length - 1; i >= 0; i--) {
5735                final int uid = uids[i];
5736                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5737                if (obj instanceof SharedUserSetting) {
5738                    final SharedUserSetting sus = (SharedUserSetting) obj;
5739                    names[i] = "shared:" + sus.name;
5740                } else if (obj instanceof PackageSetting) {
5741                    final PackageSetting ps = (PackageSetting) obj;
5742                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5743                        names[i] = null;
5744                    } else {
5745                        names[i] = ps.name;
5746                    }
5747                } else {
5748                    names[i] = null;
5749                }
5750            }
5751        }
5752        return names;
5753    }
5754
5755    @Override
5756    public int getUidForSharedUser(String sharedUserName) {
5757        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5758            return -1;
5759        }
5760        if (sharedUserName == null) {
5761            return -1;
5762        }
5763        // reader
5764        synchronized (mPackages) {
5765            SharedUserSetting suid;
5766            try {
5767                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5768                if (suid != null) {
5769                    return suid.userId;
5770                }
5771            } catch (PackageManagerException ignore) {
5772                // can't happen, but, still need to catch it
5773            }
5774            return -1;
5775        }
5776    }
5777
5778    @Override
5779    public int getFlagsForUid(int uid) {
5780        final int callingUid = Binder.getCallingUid();
5781        if (getInstantAppPackageName(callingUid) != null) {
5782            return 0;
5783        }
5784        synchronized (mPackages) {
5785            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5786            if (obj instanceof SharedUserSetting) {
5787                final SharedUserSetting sus = (SharedUserSetting) obj;
5788                return sus.pkgFlags;
5789            } else if (obj instanceof PackageSetting) {
5790                final PackageSetting ps = (PackageSetting) obj;
5791                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5792                    return 0;
5793                }
5794                return ps.pkgFlags;
5795            }
5796        }
5797        return 0;
5798    }
5799
5800    @Override
5801    public int getPrivateFlagsForUid(int uid) {
5802        final int callingUid = Binder.getCallingUid();
5803        if (getInstantAppPackageName(callingUid) != null) {
5804            return 0;
5805        }
5806        synchronized (mPackages) {
5807            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5808            if (obj instanceof SharedUserSetting) {
5809                final SharedUserSetting sus = (SharedUserSetting) obj;
5810                return sus.pkgPrivateFlags;
5811            } else if (obj instanceof PackageSetting) {
5812                final PackageSetting ps = (PackageSetting) obj;
5813                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5814                    return 0;
5815                }
5816                return ps.pkgPrivateFlags;
5817            }
5818        }
5819        return 0;
5820    }
5821
5822    @Override
5823    public boolean isUidPrivileged(int uid) {
5824        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5825            return false;
5826        }
5827        uid = UserHandle.getAppId(uid);
5828        // reader
5829        synchronized (mPackages) {
5830            Object obj = mSettings.getUserIdLPr(uid);
5831            if (obj instanceof SharedUserSetting) {
5832                final SharedUserSetting sus = (SharedUserSetting) obj;
5833                final Iterator<PackageSetting> it = sus.packages.iterator();
5834                while (it.hasNext()) {
5835                    if (it.next().isPrivileged()) {
5836                        return true;
5837                    }
5838                }
5839            } else if (obj instanceof PackageSetting) {
5840                final PackageSetting ps = (PackageSetting) obj;
5841                return ps.isPrivileged();
5842            }
5843        }
5844        return false;
5845    }
5846
5847    @Override
5848    public String[] getAppOpPermissionPackages(String permName) {
5849        return mPermissionManager.getAppOpPermissionPackages(permName);
5850    }
5851
5852    @Override
5853    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5854            int flags, int userId) {
5855        return resolveIntentInternal(
5856                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5857    }
5858
5859    /**
5860     * Normally instant apps can only be resolved when they're visible to the caller.
5861     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5862     * since we need to allow the system to start any installed application.
5863     */
5864    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5865            int flags, int userId, boolean resolveForStart) {
5866        try {
5867            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5868
5869            if (!sUserManager.exists(userId)) return null;
5870            final int callingUid = Binder.getCallingUid();
5871            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5872            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5873                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5874
5875            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5876            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5877                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5878            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5879
5880            final ResolveInfo bestChoice =
5881                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5882            return bestChoice;
5883        } finally {
5884            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5885        }
5886    }
5887
5888    @Override
5889    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5890        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5891            throw new SecurityException(
5892                    "findPersistentPreferredActivity can only be run by the system");
5893        }
5894        if (!sUserManager.exists(userId)) {
5895            return null;
5896        }
5897        final int callingUid = Binder.getCallingUid();
5898        intent = updateIntentForResolve(intent);
5899        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5900        final int flags = updateFlagsForResolve(
5901                0, userId, intent, callingUid, false /*includeInstantApps*/);
5902        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5903                userId);
5904        synchronized (mPackages) {
5905            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5906                    userId);
5907        }
5908    }
5909
5910    @Override
5911    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5912            IntentFilter filter, int match, ComponentName activity) {
5913        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5914            return;
5915        }
5916        final int userId = UserHandle.getCallingUserId();
5917        if (DEBUG_PREFERRED) {
5918            Log.v(TAG, "setLastChosenActivity intent=" + intent
5919                + " resolvedType=" + resolvedType
5920                + " flags=" + flags
5921                + " filter=" + filter
5922                + " match=" + match
5923                + " activity=" + activity);
5924            filter.dump(new PrintStreamPrinter(System.out), "    ");
5925        }
5926        intent.setComponent(null);
5927        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5928                userId);
5929        // Find any earlier preferred or last chosen entries and nuke them
5930        findPreferredActivity(intent, resolvedType,
5931                flags, query, 0, false, true, false, userId);
5932        // Add the new activity as the last chosen for this filter
5933        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5934                "Setting last chosen");
5935    }
5936
5937    @Override
5938    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5939        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5940            return null;
5941        }
5942        final int userId = UserHandle.getCallingUserId();
5943        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5944        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5945                userId);
5946        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5947                false, false, false, userId);
5948    }
5949
5950    /**
5951     * Returns whether or not instant apps have been disabled remotely.
5952     */
5953    private boolean isEphemeralDisabled() {
5954        return mEphemeralAppsDisabled;
5955    }
5956
5957    private boolean isInstantAppAllowed(
5958            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5959            boolean skipPackageCheck) {
5960        if (mInstantAppResolverConnection == null) {
5961            return false;
5962        }
5963        if (mInstantAppInstallerActivity == null) {
5964            return false;
5965        }
5966        if (intent.getComponent() != null) {
5967            return false;
5968        }
5969        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5970            return false;
5971        }
5972        if (!skipPackageCheck && intent.getPackage() != null) {
5973            return false;
5974        }
5975        final boolean isWebUri = hasWebURI(intent);
5976        if (!isWebUri || intent.getData().getHost() == null) {
5977            return false;
5978        }
5979        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5980        // Or if there's already an ephemeral app installed that handles the action
5981        synchronized (mPackages) {
5982            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5983            for (int n = 0; n < count; n++) {
5984                final ResolveInfo info = resolvedActivities.get(n);
5985                final String packageName = info.activityInfo.packageName;
5986                final PackageSetting ps = mSettings.mPackages.get(packageName);
5987                if (ps != null) {
5988                    // only check domain verification status if the app is not a browser
5989                    if (!info.handleAllWebDataURI) {
5990                        // Try to get the status from User settings first
5991                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5992                        final int status = (int) (packedStatus >> 32);
5993                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5994                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5995                            if (DEBUG_EPHEMERAL) {
5996                                Slog.v(TAG, "DENY instant app;"
5997                                    + " pkg: " + packageName + ", status: " + status);
5998                            }
5999                            return false;
6000                        }
6001                    }
6002                    if (ps.getInstantApp(userId)) {
6003                        if (DEBUG_EPHEMERAL) {
6004                            Slog.v(TAG, "DENY instant app installed;"
6005                                    + " pkg: " + packageName);
6006                        }
6007                        return false;
6008                    }
6009                }
6010            }
6011        }
6012        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6013        return true;
6014    }
6015
6016    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6017            Intent origIntent, String resolvedType, String callingPackage,
6018            Bundle verificationBundle, int userId) {
6019        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6020                new InstantAppRequest(responseObj, origIntent, resolvedType,
6021                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6022        mHandler.sendMessage(msg);
6023    }
6024
6025    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6026            int flags, List<ResolveInfo> query, int userId) {
6027        if (query != null) {
6028            final int N = query.size();
6029            if (N == 1) {
6030                return query.get(0);
6031            } else if (N > 1) {
6032                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6033                // If there is more than one activity with the same priority,
6034                // then let the user decide between them.
6035                ResolveInfo r0 = query.get(0);
6036                ResolveInfo r1 = query.get(1);
6037                if (DEBUG_INTENT_MATCHING || debug) {
6038                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6039                            + r1.activityInfo.name + "=" + r1.priority);
6040                }
6041                // If the first activity has a higher priority, or a different
6042                // default, then it is always desirable to pick it.
6043                if (r0.priority != r1.priority
6044                        || r0.preferredOrder != r1.preferredOrder
6045                        || r0.isDefault != r1.isDefault) {
6046                    return query.get(0);
6047                }
6048                // If we have saved a preference for a preferred activity for
6049                // this Intent, use that.
6050                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6051                        flags, query, r0.priority, true, false, debug, userId);
6052                if (ri != null) {
6053                    return ri;
6054                }
6055                // If we have an ephemeral app, use it
6056                for (int i = 0; i < N; i++) {
6057                    ri = query.get(i);
6058                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6059                        final String packageName = ri.activityInfo.packageName;
6060                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6061                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6062                        final int status = (int)(packedStatus >> 32);
6063                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6064                            return ri;
6065                        }
6066                    }
6067                }
6068                ri = new ResolveInfo(mResolveInfo);
6069                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6070                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6071                // If all of the options come from the same package, show the application's
6072                // label and icon instead of the generic resolver's.
6073                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6074                // and then throw away the ResolveInfo itself, meaning that the caller loses
6075                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6076                // a fallback for this case; we only set the target package's resources on
6077                // the ResolveInfo, not the ActivityInfo.
6078                final String intentPackage = intent.getPackage();
6079                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6080                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6081                    ri.resolvePackageName = intentPackage;
6082                    if (userNeedsBadging(userId)) {
6083                        ri.noResourceId = true;
6084                    } else {
6085                        ri.icon = appi.icon;
6086                    }
6087                    ri.iconResourceId = appi.icon;
6088                    ri.labelRes = appi.labelRes;
6089                }
6090                ri.activityInfo.applicationInfo = new ApplicationInfo(
6091                        ri.activityInfo.applicationInfo);
6092                if (userId != 0) {
6093                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6094                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6095                }
6096                // Make sure that the resolver is displayable in car mode
6097                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6098                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6099                return ri;
6100            }
6101        }
6102        return null;
6103    }
6104
6105    /**
6106     * Return true if the given list is not empty and all of its contents have
6107     * an activityInfo with the given package name.
6108     */
6109    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6110        if (ArrayUtils.isEmpty(list)) {
6111            return false;
6112        }
6113        for (int i = 0, N = list.size(); i < N; i++) {
6114            final ResolveInfo ri = list.get(i);
6115            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6116            if (ai == null || !packageName.equals(ai.packageName)) {
6117                return false;
6118            }
6119        }
6120        return true;
6121    }
6122
6123    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6124            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6125        final int N = query.size();
6126        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6127                .get(userId);
6128        // Get the list of persistent preferred activities that handle the intent
6129        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6130        List<PersistentPreferredActivity> pprefs = ppir != null
6131                ? ppir.queryIntent(intent, resolvedType,
6132                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6133                        userId)
6134                : null;
6135        if (pprefs != null && pprefs.size() > 0) {
6136            final int M = pprefs.size();
6137            for (int i=0; i<M; i++) {
6138                final PersistentPreferredActivity ppa = pprefs.get(i);
6139                if (DEBUG_PREFERRED || debug) {
6140                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6141                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6142                            + "\n  component=" + ppa.mComponent);
6143                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6144                }
6145                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6146                        flags | MATCH_DISABLED_COMPONENTS, userId);
6147                if (DEBUG_PREFERRED || debug) {
6148                    Slog.v(TAG, "Found persistent preferred activity:");
6149                    if (ai != null) {
6150                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6151                    } else {
6152                        Slog.v(TAG, "  null");
6153                    }
6154                }
6155                if (ai == null) {
6156                    // This previously registered persistent preferred activity
6157                    // component is no longer known. Ignore it and do NOT remove it.
6158                    continue;
6159                }
6160                for (int j=0; j<N; j++) {
6161                    final ResolveInfo ri = query.get(j);
6162                    if (!ri.activityInfo.applicationInfo.packageName
6163                            .equals(ai.applicationInfo.packageName)) {
6164                        continue;
6165                    }
6166                    if (!ri.activityInfo.name.equals(ai.name)) {
6167                        continue;
6168                    }
6169                    //  Found a persistent preference that can handle the intent.
6170                    if (DEBUG_PREFERRED || debug) {
6171                        Slog.v(TAG, "Returning persistent preferred activity: " +
6172                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6173                    }
6174                    return ri;
6175                }
6176            }
6177        }
6178        return null;
6179    }
6180
6181    // TODO: handle preferred activities missing while user has amnesia
6182    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6183            List<ResolveInfo> query, int priority, boolean always,
6184            boolean removeMatches, boolean debug, int userId) {
6185        if (!sUserManager.exists(userId)) return null;
6186        final int callingUid = Binder.getCallingUid();
6187        flags = updateFlagsForResolve(
6188                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6189        intent = updateIntentForResolve(intent);
6190        // writer
6191        synchronized (mPackages) {
6192            // Try to find a matching persistent preferred activity.
6193            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6194                    debug, userId);
6195
6196            // If a persistent preferred activity matched, use it.
6197            if (pri != null) {
6198                return pri;
6199            }
6200
6201            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6202            // Get the list of preferred activities that handle the intent
6203            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6204            List<PreferredActivity> prefs = pir != null
6205                    ? pir.queryIntent(intent, resolvedType,
6206                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6207                            userId)
6208                    : null;
6209            if (prefs != null && prefs.size() > 0) {
6210                boolean changed = false;
6211                try {
6212                    // First figure out how good the original match set is.
6213                    // We will only allow preferred activities that came
6214                    // from the same match quality.
6215                    int match = 0;
6216
6217                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6218
6219                    final int N = query.size();
6220                    for (int j=0; j<N; j++) {
6221                        final ResolveInfo ri = query.get(j);
6222                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6223                                + ": 0x" + Integer.toHexString(match));
6224                        if (ri.match > match) {
6225                            match = ri.match;
6226                        }
6227                    }
6228
6229                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6230                            + Integer.toHexString(match));
6231
6232                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6233                    final int M = prefs.size();
6234                    for (int i=0; i<M; i++) {
6235                        final PreferredActivity pa = prefs.get(i);
6236                        if (DEBUG_PREFERRED || debug) {
6237                            Slog.v(TAG, "Checking PreferredActivity ds="
6238                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6239                                    + "\n  component=" + pa.mPref.mComponent);
6240                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6241                        }
6242                        if (pa.mPref.mMatch != match) {
6243                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6244                                    + Integer.toHexString(pa.mPref.mMatch));
6245                            continue;
6246                        }
6247                        // If it's not an "always" type preferred activity and that's what we're
6248                        // looking for, skip it.
6249                        if (always && !pa.mPref.mAlways) {
6250                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6251                            continue;
6252                        }
6253                        final ActivityInfo ai = getActivityInfo(
6254                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6255                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6256                                userId);
6257                        if (DEBUG_PREFERRED || debug) {
6258                            Slog.v(TAG, "Found preferred activity:");
6259                            if (ai != null) {
6260                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6261                            } else {
6262                                Slog.v(TAG, "  null");
6263                            }
6264                        }
6265                        if (ai == null) {
6266                            // This previously registered preferred activity
6267                            // component is no longer known.  Most likely an update
6268                            // to the app was installed and in the new version this
6269                            // component no longer exists.  Clean it up by removing
6270                            // it from the preferred activities list, and skip it.
6271                            Slog.w(TAG, "Removing dangling preferred activity: "
6272                                    + pa.mPref.mComponent);
6273                            pir.removeFilter(pa);
6274                            changed = true;
6275                            continue;
6276                        }
6277                        for (int j=0; j<N; j++) {
6278                            final ResolveInfo ri = query.get(j);
6279                            if (!ri.activityInfo.applicationInfo.packageName
6280                                    .equals(ai.applicationInfo.packageName)) {
6281                                continue;
6282                            }
6283                            if (!ri.activityInfo.name.equals(ai.name)) {
6284                                continue;
6285                            }
6286
6287                            if (removeMatches) {
6288                                pir.removeFilter(pa);
6289                                changed = true;
6290                                if (DEBUG_PREFERRED) {
6291                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6292                                }
6293                                break;
6294                            }
6295
6296                            // Okay we found a previously set preferred or last chosen app.
6297                            // If the result set is different from when this
6298                            // was created, and is not a subset of the preferred set, we need to
6299                            // clear it and re-ask the user their preference, if we're looking for
6300                            // an "always" type entry.
6301                            if (always && !pa.mPref.sameSet(query)) {
6302                                if (pa.mPref.isSuperset(query)) {
6303                                    // some components of the set are no longer present in
6304                                    // the query, but the preferred activity can still be reused
6305                                    if (DEBUG_PREFERRED) {
6306                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6307                                                + " still valid as only non-preferred components"
6308                                                + " were removed for " + intent + " type "
6309                                                + resolvedType);
6310                                    }
6311                                    // remove obsolete components and re-add the up-to-date filter
6312                                    PreferredActivity freshPa = new PreferredActivity(pa,
6313                                            pa.mPref.mMatch,
6314                                            pa.mPref.discardObsoleteComponents(query),
6315                                            pa.mPref.mComponent,
6316                                            pa.mPref.mAlways);
6317                                    pir.removeFilter(pa);
6318                                    pir.addFilter(freshPa);
6319                                    changed = true;
6320                                } else {
6321                                    Slog.i(TAG,
6322                                            "Result set changed, dropping preferred activity for "
6323                                                    + intent + " type " + resolvedType);
6324                                    if (DEBUG_PREFERRED) {
6325                                        Slog.v(TAG, "Removing preferred activity since set changed "
6326                                                + pa.mPref.mComponent);
6327                                    }
6328                                    pir.removeFilter(pa);
6329                                    // Re-add the filter as a "last chosen" entry (!always)
6330                                    PreferredActivity lastChosen = new PreferredActivity(
6331                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6332                                    pir.addFilter(lastChosen);
6333                                    changed = true;
6334                                    return null;
6335                                }
6336                            }
6337
6338                            // Yay! Either the set matched or we're looking for the last chosen
6339                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6340                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6341                            return ri;
6342                        }
6343                    }
6344                } finally {
6345                    if (changed) {
6346                        if (DEBUG_PREFERRED) {
6347                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6348                        }
6349                        scheduleWritePackageRestrictionsLocked(userId);
6350                    }
6351                }
6352            }
6353        }
6354        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6355        return null;
6356    }
6357
6358    /*
6359     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6360     */
6361    @Override
6362    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6363            int targetUserId) {
6364        mContext.enforceCallingOrSelfPermission(
6365                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6366        List<CrossProfileIntentFilter> matches =
6367                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6368        if (matches != null) {
6369            int size = matches.size();
6370            for (int i = 0; i < size; i++) {
6371                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6372            }
6373        }
6374        if (hasWebURI(intent)) {
6375            // cross-profile app linking works only towards the parent.
6376            final int callingUid = Binder.getCallingUid();
6377            final UserInfo parent = getProfileParent(sourceUserId);
6378            synchronized(mPackages) {
6379                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6380                        false /*includeInstantApps*/);
6381                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6382                        intent, resolvedType, flags, sourceUserId, parent.id);
6383                return xpDomainInfo != null;
6384            }
6385        }
6386        return false;
6387    }
6388
6389    private UserInfo getProfileParent(int userId) {
6390        final long identity = Binder.clearCallingIdentity();
6391        try {
6392            return sUserManager.getProfileParent(userId);
6393        } finally {
6394            Binder.restoreCallingIdentity(identity);
6395        }
6396    }
6397
6398    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6399            String resolvedType, int userId) {
6400        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6401        if (resolver != null) {
6402            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6403        }
6404        return null;
6405    }
6406
6407    @Override
6408    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6409            String resolvedType, int flags, int userId) {
6410        try {
6411            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6412
6413            return new ParceledListSlice<>(
6414                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6415        } finally {
6416            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6417        }
6418    }
6419
6420    /**
6421     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6422     * instant, returns {@code null}.
6423     */
6424    private String getInstantAppPackageName(int callingUid) {
6425        synchronized (mPackages) {
6426            // If the caller is an isolated app use the owner's uid for the lookup.
6427            if (Process.isIsolated(callingUid)) {
6428                callingUid = mIsolatedOwners.get(callingUid);
6429            }
6430            final int appId = UserHandle.getAppId(callingUid);
6431            final Object obj = mSettings.getUserIdLPr(appId);
6432            if (obj instanceof PackageSetting) {
6433                final PackageSetting ps = (PackageSetting) obj;
6434                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6435                return isInstantApp ? ps.pkg.packageName : null;
6436            }
6437        }
6438        return null;
6439    }
6440
6441    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6442            String resolvedType, int flags, int userId) {
6443        return queryIntentActivitiesInternal(
6444                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6445                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6446    }
6447
6448    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6449            String resolvedType, int flags, int filterCallingUid, int userId,
6450            boolean resolveForStart, boolean allowDynamicSplits) {
6451        if (!sUserManager.exists(userId)) return Collections.emptyList();
6452        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6453        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6454                false /* requireFullPermission */, false /* checkShell */,
6455                "query intent activities");
6456        final String pkgName = intent.getPackage();
6457        ComponentName comp = intent.getComponent();
6458        if (comp == null) {
6459            if (intent.getSelector() != null) {
6460                intent = intent.getSelector();
6461                comp = intent.getComponent();
6462            }
6463        }
6464
6465        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6466                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6467        if (comp != null) {
6468            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6469            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6470            if (ai != null) {
6471                // When specifying an explicit component, we prevent the activity from being
6472                // used when either 1) the calling package is normal and the activity is within
6473                // an ephemeral application or 2) the calling package is ephemeral and the
6474                // activity is not visible to ephemeral applications.
6475                final boolean matchInstantApp =
6476                        (flags & PackageManager.MATCH_INSTANT) != 0;
6477                final boolean matchVisibleToInstantAppOnly =
6478                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6479                final boolean matchExplicitlyVisibleOnly =
6480                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6481                final boolean isCallerInstantApp =
6482                        instantAppPkgName != null;
6483                final boolean isTargetSameInstantApp =
6484                        comp.getPackageName().equals(instantAppPkgName);
6485                final boolean isTargetInstantApp =
6486                        (ai.applicationInfo.privateFlags
6487                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6488                final boolean isTargetVisibleToInstantApp =
6489                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6490                final boolean isTargetExplicitlyVisibleToInstantApp =
6491                        isTargetVisibleToInstantApp
6492                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6493                final boolean isTargetHiddenFromInstantApp =
6494                        !isTargetVisibleToInstantApp
6495                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6496                final boolean blockResolution =
6497                        !isTargetSameInstantApp
6498                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6499                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6500                                        && isTargetHiddenFromInstantApp));
6501                if (!blockResolution) {
6502                    final ResolveInfo ri = new ResolveInfo();
6503                    ri.activityInfo = ai;
6504                    list.add(ri);
6505                }
6506            }
6507            return applyPostResolutionFilter(
6508                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6509        }
6510
6511        // reader
6512        boolean sortResult = false;
6513        boolean addEphemeral = false;
6514        List<ResolveInfo> result;
6515        final boolean ephemeralDisabled = isEphemeralDisabled();
6516        synchronized (mPackages) {
6517            if (pkgName == null) {
6518                List<CrossProfileIntentFilter> matchingFilters =
6519                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6520                // Check for results that need to skip the current profile.
6521                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6522                        resolvedType, flags, userId);
6523                if (xpResolveInfo != null) {
6524                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6525                    xpResult.add(xpResolveInfo);
6526                    return applyPostResolutionFilter(
6527                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6528                            allowDynamicSplits, filterCallingUid, userId);
6529                }
6530
6531                // Check for results in the current profile.
6532                result = filterIfNotSystemUser(mActivities.queryIntent(
6533                        intent, resolvedType, flags, userId), userId);
6534                addEphemeral = !ephemeralDisabled
6535                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6536                // Check for cross profile results.
6537                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6538                xpResolveInfo = queryCrossProfileIntents(
6539                        matchingFilters, intent, resolvedType, flags, userId,
6540                        hasNonNegativePriorityResult);
6541                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6542                    boolean isVisibleToUser = filterIfNotSystemUser(
6543                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6544                    if (isVisibleToUser) {
6545                        result.add(xpResolveInfo);
6546                        sortResult = true;
6547                    }
6548                }
6549                if (hasWebURI(intent)) {
6550                    CrossProfileDomainInfo xpDomainInfo = null;
6551                    final UserInfo parent = getProfileParent(userId);
6552                    if (parent != null) {
6553                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6554                                flags, userId, parent.id);
6555                    }
6556                    if (xpDomainInfo != null) {
6557                        if (xpResolveInfo != null) {
6558                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6559                            // in the result.
6560                            result.remove(xpResolveInfo);
6561                        }
6562                        if (result.size() == 0 && !addEphemeral) {
6563                            // No result in current profile, but found candidate in parent user.
6564                            // And we are not going to add emphemeral app, so we can return the
6565                            // result straight away.
6566                            result.add(xpDomainInfo.resolveInfo);
6567                            return applyPostResolutionFilter(result, instantAppPkgName,
6568                                    allowDynamicSplits, filterCallingUid, userId);
6569                        }
6570                    } else if (result.size() <= 1 && !addEphemeral) {
6571                        // No result in parent user and <= 1 result in current profile, and we
6572                        // are not going to add emphemeral app, so we can return the result without
6573                        // further processing.
6574                        return applyPostResolutionFilter(result, instantAppPkgName,
6575                                allowDynamicSplits, filterCallingUid, userId);
6576                    }
6577                    // We have more than one candidate (combining results from current and parent
6578                    // profile), so we need filtering and sorting.
6579                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6580                            intent, flags, result, xpDomainInfo, userId);
6581                    sortResult = true;
6582                }
6583            } else {
6584                final PackageParser.Package pkg = mPackages.get(pkgName);
6585                result = null;
6586                if (pkg != null) {
6587                    result = filterIfNotSystemUser(
6588                            mActivities.queryIntentForPackage(
6589                                    intent, resolvedType, flags, pkg.activities, userId),
6590                            userId);
6591                }
6592                if (result == null || result.size() == 0) {
6593                    // the caller wants to resolve for a particular package; however, there
6594                    // were no installed results, so, try to find an ephemeral result
6595                    addEphemeral = !ephemeralDisabled
6596                            && isInstantAppAllowed(
6597                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6598                    if (result == null) {
6599                        result = new ArrayList<>();
6600                    }
6601                }
6602            }
6603        }
6604        if (addEphemeral) {
6605            result = maybeAddInstantAppInstaller(
6606                    result, intent, resolvedType, flags, userId, resolveForStart);
6607        }
6608        if (sortResult) {
6609            Collections.sort(result, mResolvePrioritySorter);
6610        }
6611        return applyPostResolutionFilter(
6612                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6613    }
6614
6615    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6616            String resolvedType, int flags, int userId, boolean resolveForStart) {
6617        // first, check to see if we've got an instant app already installed
6618        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6619        ResolveInfo localInstantApp = null;
6620        boolean blockResolution = false;
6621        if (!alreadyResolvedLocally) {
6622            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6623                    flags
6624                        | PackageManager.GET_RESOLVED_FILTER
6625                        | PackageManager.MATCH_INSTANT
6626                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6627                    userId);
6628            for (int i = instantApps.size() - 1; i >= 0; --i) {
6629                final ResolveInfo info = instantApps.get(i);
6630                final String packageName = info.activityInfo.packageName;
6631                final PackageSetting ps = mSettings.mPackages.get(packageName);
6632                if (ps.getInstantApp(userId)) {
6633                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6634                    final int status = (int)(packedStatus >> 32);
6635                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6636                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6637                        // there's a local instant application installed, but, the user has
6638                        // chosen to never use it; skip resolution and don't acknowledge
6639                        // an instant application is even available
6640                        if (DEBUG_EPHEMERAL) {
6641                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6642                        }
6643                        blockResolution = true;
6644                        break;
6645                    } else {
6646                        // we have a locally installed instant application; skip resolution
6647                        // but acknowledge there's an instant application available
6648                        if (DEBUG_EPHEMERAL) {
6649                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6650                        }
6651                        localInstantApp = info;
6652                        break;
6653                    }
6654                }
6655            }
6656        }
6657        // no app installed, let's see if one's available
6658        AuxiliaryResolveInfo auxiliaryResponse = null;
6659        if (!blockResolution) {
6660            if (localInstantApp == null) {
6661                // we don't have an instant app locally, resolve externally
6662                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6663                final InstantAppRequest requestObject = new InstantAppRequest(
6664                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6665                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6666                        resolveForStart);
6667                auxiliaryResponse =
6668                        InstantAppResolver.doInstantAppResolutionPhaseOne(
6669                                mContext, mInstantAppResolverConnection, requestObject);
6670                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6671            } else {
6672                // we have an instant application locally, but, we can't admit that since
6673                // callers shouldn't be able to determine prior browsing. create a dummy
6674                // auxiliary response so the downstream code behaves as if there's an
6675                // instant application available externally. when it comes time to start
6676                // the instant application, we'll do the right thing.
6677                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6678                auxiliaryResponse = new AuxiliaryResolveInfo(
6679                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
6680                        ai.versionCode, null /*failureIntent*/);
6681            }
6682        }
6683        if (auxiliaryResponse != null) {
6684            if (DEBUG_EPHEMERAL) {
6685                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6686            }
6687            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6688            final PackageSetting ps =
6689                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6690            if (ps != null) {
6691                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6692                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6693                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6694                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6695                // make sure this resolver is the default
6696                ephemeralInstaller.isDefault = true;
6697                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6698                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6699                // add a non-generic filter
6700                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6701                ephemeralInstaller.filter.addDataPath(
6702                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6703                ephemeralInstaller.isInstantAppAvailable = true;
6704                result.add(ephemeralInstaller);
6705            }
6706        }
6707        return result;
6708    }
6709
6710    private static class CrossProfileDomainInfo {
6711        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6712        ResolveInfo resolveInfo;
6713        /* Best domain verification status of the activities found in the other profile */
6714        int bestDomainVerificationStatus;
6715    }
6716
6717    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6718            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6719        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6720                sourceUserId)) {
6721            return null;
6722        }
6723        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6724                resolvedType, flags, parentUserId);
6725
6726        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6727            return null;
6728        }
6729        CrossProfileDomainInfo result = null;
6730        int size = resultTargetUser.size();
6731        for (int i = 0; i < size; i++) {
6732            ResolveInfo riTargetUser = resultTargetUser.get(i);
6733            // Intent filter verification is only for filters that specify a host. So don't return
6734            // those that handle all web uris.
6735            if (riTargetUser.handleAllWebDataURI) {
6736                continue;
6737            }
6738            String packageName = riTargetUser.activityInfo.packageName;
6739            PackageSetting ps = mSettings.mPackages.get(packageName);
6740            if (ps == null) {
6741                continue;
6742            }
6743            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6744            int status = (int)(verificationState >> 32);
6745            if (result == null) {
6746                result = new CrossProfileDomainInfo();
6747                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6748                        sourceUserId, parentUserId);
6749                result.bestDomainVerificationStatus = status;
6750            } else {
6751                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6752                        result.bestDomainVerificationStatus);
6753            }
6754        }
6755        // Don't consider matches with status NEVER across profiles.
6756        if (result != null && result.bestDomainVerificationStatus
6757                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6758            return null;
6759        }
6760        return result;
6761    }
6762
6763    /**
6764     * Verification statuses are ordered from the worse to the best, except for
6765     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6766     */
6767    private int bestDomainVerificationStatus(int status1, int status2) {
6768        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6769            return status2;
6770        }
6771        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6772            return status1;
6773        }
6774        return (int) MathUtils.max(status1, status2);
6775    }
6776
6777    private boolean isUserEnabled(int userId) {
6778        long callingId = Binder.clearCallingIdentity();
6779        try {
6780            UserInfo userInfo = sUserManager.getUserInfo(userId);
6781            return userInfo != null && userInfo.isEnabled();
6782        } finally {
6783            Binder.restoreCallingIdentity(callingId);
6784        }
6785    }
6786
6787    /**
6788     * Filter out activities with systemUserOnly flag set, when current user is not System.
6789     *
6790     * @return filtered list
6791     */
6792    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6793        if (userId == UserHandle.USER_SYSTEM) {
6794            return resolveInfos;
6795        }
6796        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6797            ResolveInfo info = resolveInfos.get(i);
6798            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6799                resolveInfos.remove(i);
6800            }
6801        }
6802        return resolveInfos;
6803    }
6804
6805    /**
6806     * Filters out ephemeral activities.
6807     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6808     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6809     *
6810     * @param resolveInfos The pre-filtered list of resolved activities
6811     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6812     *          is performed.
6813     * @return A filtered list of resolved activities.
6814     */
6815    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6816            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
6817        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6818            final ResolveInfo info = resolveInfos.get(i);
6819            // allow activities that are defined in the provided package
6820            if (allowDynamicSplits
6821                    && info.activityInfo.splitName != null
6822                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6823                            info.activityInfo.splitName)) {
6824                if (mInstantAppInstallerInfo == null) {
6825                    if (DEBUG_INSTALL) {
6826                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6827                    }
6828                    resolveInfos.remove(i);
6829                    continue;
6830                }
6831                // requested activity is defined in a split that hasn't been installed yet.
6832                // add the installer to the resolve list
6833                if (DEBUG_INSTALL) {
6834                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6835                }
6836                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6837                final ComponentName installFailureActivity = findInstallFailureActivity(
6838                        info.activityInfo.packageName,  filterCallingUid, userId);
6839                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6840                        info.activityInfo.packageName, info.activityInfo.splitName,
6841                        installFailureActivity,
6842                        info.activityInfo.applicationInfo.versionCode,
6843                        null /*failureIntent*/);
6844                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6845                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6846                // add a non-generic filter
6847                installerInfo.filter = new IntentFilter();
6848
6849                // This resolve info may appear in the chooser UI, so let us make it
6850                // look as the one it replaces as far as the user is concerned which
6851                // requires loading the correct label and icon for the resolve info.
6852                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6853                installerInfo.labelRes = info.resolveLabelResId();
6854                installerInfo.icon = info.resolveIconResId();
6855
6856                // propagate priority/preferred order/default
6857                installerInfo.priority = info.priority;
6858                installerInfo.preferredOrder = info.preferredOrder;
6859                installerInfo.isDefault = info.isDefault;
6860                resolveInfos.set(i, installerInfo);
6861                continue;
6862            }
6863            // caller is a full app, don't need to apply any other filtering
6864            if (ephemeralPkgName == null) {
6865                continue;
6866            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6867                // caller is same app; don't need to apply any other filtering
6868                continue;
6869            }
6870            // allow activities that have been explicitly exposed to ephemeral apps
6871            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6872            if (!isEphemeralApp
6873                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6874                continue;
6875            }
6876            resolveInfos.remove(i);
6877        }
6878        return resolveInfos;
6879    }
6880
6881    /**
6882     * Returns the activity component that can handle install failures.
6883     * <p>By default, the instant application installer handles failures. However, an
6884     * application may want to handle failures on its own. Applications do this by
6885     * creating an activity with an intent filter that handles the action
6886     * {@link Intent#ACTION_INSTALL_FAILURE}.
6887     */
6888    private @Nullable ComponentName findInstallFailureActivity(
6889            String packageName, int filterCallingUid, int userId) {
6890        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6891        failureActivityIntent.setPackage(packageName);
6892        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6893        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6894                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6895                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6896        final int NR = result.size();
6897        if (NR > 0) {
6898            for (int i = 0; i < NR; i++) {
6899                final ResolveInfo info = result.get(i);
6900                if (info.activityInfo.splitName != null) {
6901                    continue;
6902                }
6903                return new ComponentName(packageName, info.activityInfo.name);
6904            }
6905        }
6906        return null;
6907    }
6908
6909    /**
6910     * @param resolveInfos list of resolve infos in descending priority order
6911     * @return if the list contains a resolve info with non-negative priority
6912     */
6913    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6914        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6915    }
6916
6917    private static boolean hasWebURI(Intent intent) {
6918        if (intent.getData() == null) {
6919            return false;
6920        }
6921        final String scheme = intent.getScheme();
6922        if (TextUtils.isEmpty(scheme)) {
6923            return false;
6924        }
6925        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6926    }
6927
6928    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6929            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6930            int userId) {
6931        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6932
6933        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6934            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6935                    candidates.size());
6936        }
6937
6938        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6939        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6940        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6941        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6942        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6943        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6944
6945        synchronized (mPackages) {
6946            final int count = candidates.size();
6947            // First, try to use linked apps. Partition the candidates into four lists:
6948            // one for the final results, one for the "do not use ever", one for "undefined status"
6949            // and finally one for "browser app type".
6950            for (int n=0; n<count; n++) {
6951                ResolveInfo info = candidates.get(n);
6952                String packageName = info.activityInfo.packageName;
6953                PackageSetting ps = mSettings.mPackages.get(packageName);
6954                if (ps != null) {
6955                    // Add to the special match all list (Browser use case)
6956                    if (info.handleAllWebDataURI) {
6957                        matchAllList.add(info);
6958                        continue;
6959                    }
6960                    // Try to get the status from User settings first
6961                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6962                    int status = (int)(packedStatus >> 32);
6963                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6964                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6965                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6966                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6967                                    + " : linkgen=" + linkGeneration);
6968                        }
6969                        // Use link-enabled generation as preferredOrder, i.e.
6970                        // prefer newly-enabled over earlier-enabled.
6971                        info.preferredOrder = linkGeneration;
6972                        alwaysList.add(info);
6973                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6974                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6975                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6976                        }
6977                        neverList.add(info);
6978                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6979                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6980                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6981                        }
6982                        alwaysAskList.add(info);
6983                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6984                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6985                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6986                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6987                        }
6988                        undefinedList.add(info);
6989                    }
6990                }
6991            }
6992
6993            // We'll want to include browser possibilities in a few cases
6994            boolean includeBrowser = false;
6995
6996            // First try to add the "always" resolution(s) for the current user, if any
6997            if (alwaysList.size() > 0) {
6998                result.addAll(alwaysList);
6999            } else {
7000                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7001                result.addAll(undefinedList);
7002                // Maybe add one for the other profile.
7003                if (xpDomainInfo != null && (
7004                        xpDomainInfo.bestDomainVerificationStatus
7005                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7006                    result.add(xpDomainInfo.resolveInfo);
7007                }
7008                includeBrowser = true;
7009            }
7010
7011            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7012            // If there were 'always' entries their preferred order has been set, so we also
7013            // back that off to make the alternatives equivalent
7014            if (alwaysAskList.size() > 0) {
7015                for (ResolveInfo i : result) {
7016                    i.preferredOrder = 0;
7017                }
7018                result.addAll(alwaysAskList);
7019                includeBrowser = true;
7020            }
7021
7022            if (includeBrowser) {
7023                // Also add browsers (all of them or only the default one)
7024                if (DEBUG_DOMAIN_VERIFICATION) {
7025                    Slog.v(TAG, "   ...including browsers in candidate set");
7026                }
7027                if ((matchFlags & MATCH_ALL) != 0) {
7028                    result.addAll(matchAllList);
7029                } else {
7030                    // Browser/generic handling case.  If there's a default browser, go straight
7031                    // to that (but only if there is no other higher-priority match).
7032                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7033                    int maxMatchPrio = 0;
7034                    ResolveInfo defaultBrowserMatch = null;
7035                    final int numCandidates = matchAllList.size();
7036                    for (int n = 0; n < numCandidates; n++) {
7037                        ResolveInfo info = matchAllList.get(n);
7038                        // track the highest overall match priority...
7039                        if (info.priority > maxMatchPrio) {
7040                            maxMatchPrio = info.priority;
7041                        }
7042                        // ...and the highest-priority default browser match
7043                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7044                            if (defaultBrowserMatch == null
7045                                    || (defaultBrowserMatch.priority < info.priority)) {
7046                                if (debug) {
7047                                    Slog.v(TAG, "Considering default browser match " + info);
7048                                }
7049                                defaultBrowserMatch = info;
7050                            }
7051                        }
7052                    }
7053                    if (defaultBrowserMatch != null
7054                            && defaultBrowserMatch.priority >= maxMatchPrio
7055                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7056                    {
7057                        if (debug) {
7058                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7059                        }
7060                        result.add(defaultBrowserMatch);
7061                    } else {
7062                        result.addAll(matchAllList);
7063                    }
7064                }
7065
7066                // If there is nothing selected, add all candidates and remove the ones that the user
7067                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7068                if (result.size() == 0) {
7069                    result.addAll(candidates);
7070                    result.removeAll(neverList);
7071                }
7072            }
7073        }
7074        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7075            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7076                    result.size());
7077            for (ResolveInfo info : result) {
7078                Slog.v(TAG, "  + " + info.activityInfo);
7079            }
7080        }
7081        return result;
7082    }
7083
7084    // Returns a packed value as a long:
7085    //
7086    // high 'int'-sized word: link status: undefined/ask/never/always.
7087    // low 'int'-sized word: relative priority among 'always' results.
7088    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7089        long result = ps.getDomainVerificationStatusForUser(userId);
7090        // if none available, get the master status
7091        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7092            if (ps.getIntentFilterVerificationInfo() != null) {
7093                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7094            }
7095        }
7096        return result;
7097    }
7098
7099    private ResolveInfo querySkipCurrentProfileIntents(
7100            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7101            int flags, int sourceUserId) {
7102        if (matchingFilters != null) {
7103            int size = matchingFilters.size();
7104            for (int i = 0; i < size; i ++) {
7105                CrossProfileIntentFilter filter = matchingFilters.get(i);
7106                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7107                    // Checking if there are activities in the target user that can handle the
7108                    // intent.
7109                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7110                            resolvedType, flags, sourceUserId);
7111                    if (resolveInfo != null) {
7112                        return resolveInfo;
7113                    }
7114                }
7115            }
7116        }
7117        return null;
7118    }
7119
7120    // Return matching ResolveInfo in target user if any.
7121    private ResolveInfo queryCrossProfileIntents(
7122            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7123            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7124        if (matchingFilters != null) {
7125            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7126            // match the same intent. For performance reasons, it is better not to
7127            // run queryIntent twice for the same userId
7128            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7129            int size = matchingFilters.size();
7130            for (int i = 0; i < size; i++) {
7131                CrossProfileIntentFilter filter = matchingFilters.get(i);
7132                int targetUserId = filter.getTargetUserId();
7133                boolean skipCurrentProfile =
7134                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7135                boolean skipCurrentProfileIfNoMatchFound =
7136                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7137                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7138                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7139                    // Checking if there are activities in the target user that can handle the
7140                    // intent.
7141                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7142                            resolvedType, flags, sourceUserId);
7143                    if (resolveInfo != null) return resolveInfo;
7144                    alreadyTriedUserIds.put(targetUserId, true);
7145                }
7146            }
7147        }
7148        return null;
7149    }
7150
7151    /**
7152     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7153     * will forward the intent to the filter's target user.
7154     * Otherwise, returns null.
7155     */
7156    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7157            String resolvedType, int flags, int sourceUserId) {
7158        int targetUserId = filter.getTargetUserId();
7159        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7160                resolvedType, flags, targetUserId);
7161        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7162            // If all the matches in the target profile are suspended, return null.
7163            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7164                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7165                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7166                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7167                            targetUserId);
7168                }
7169            }
7170        }
7171        return null;
7172    }
7173
7174    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7175            int sourceUserId, int targetUserId) {
7176        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7177        long ident = Binder.clearCallingIdentity();
7178        boolean targetIsProfile;
7179        try {
7180            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7181        } finally {
7182            Binder.restoreCallingIdentity(ident);
7183        }
7184        String className;
7185        if (targetIsProfile) {
7186            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7187        } else {
7188            className = FORWARD_INTENT_TO_PARENT;
7189        }
7190        ComponentName forwardingActivityComponentName = new ComponentName(
7191                mAndroidApplication.packageName, className);
7192        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7193                sourceUserId);
7194        if (!targetIsProfile) {
7195            forwardingActivityInfo.showUserIcon = targetUserId;
7196            forwardingResolveInfo.noResourceId = true;
7197        }
7198        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7199        forwardingResolveInfo.priority = 0;
7200        forwardingResolveInfo.preferredOrder = 0;
7201        forwardingResolveInfo.match = 0;
7202        forwardingResolveInfo.isDefault = true;
7203        forwardingResolveInfo.filter = filter;
7204        forwardingResolveInfo.targetUserId = targetUserId;
7205        return forwardingResolveInfo;
7206    }
7207
7208    @Override
7209    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7210            Intent[] specifics, String[] specificTypes, Intent intent,
7211            String resolvedType, int flags, int userId) {
7212        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7213                specificTypes, intent, resolvedType, flags, userId));
7214    }
7215
7216    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7217            Intent[] specifics, String[] specificTypes, Intent intent,
7218            String resolvedType, int flags, int userId) {
7219        if (!sUserManager.exists(userId)) return Collections.emptyList();
7220        final int callingUid = Binder.getCallingUid();
7221        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7222                false /*includeInstantApps*/);
7223        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7224                false /*requireFullPermission*/, false /*checkShell*/,
7225                "query intent activity options");
7226        final String resultsAction = intent.getAction();
7227
7228        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7229                | PackageManager.GET_RESOLVED_FILTER, userId);
7230
7231        if (DEBUG_INTENT_MATCHING) {
7232            Log.v(TAG, "Query " + intent + ": " + results);
7233        }
7234
7235        int specificsPos = 0;
7236        int N;
7237
7238        // todo: note that the algorithm used here is O(N^2).  This
7239        // isn't a problem in our current environment, but if we start running
7240        // into situations where we have more than 5 or 10 matches then this
7241        // should probably be changed to something smarter...
7242
7243        // First we go through and resolve each of the specific items
7244        // that were supplied, taking care of removing any corresponding
7245        // duplicate items in the generic resolve list.
7246        if (specifics != null) {
7247            for (int i=0; i<specifics.length; i++) {
7248                final Intent sintent = specifics[i];
7249                if (sintent == null) {
7250                    continue;
7251                }
7252
7253                if (DEBUG_INTENT_MATCHING) {
7254                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7255                }
7256
7257                String action = sintent.getAction();
7258                if (resultsAction != null && resultsAction.equals(action)) {
7259                    // If this action was explicitly requested, then don't
7260                    // remove things that have it.
7261                    action = null;
7262                }
7263
7264                ResolveInfo ri = null;
7265                ActivityInfo ai = null;
7266
7267                ComponentName comp = sintent.getComponent();
7268                if (comp == null) {
7269                    ri = resolveIntent(
7270                        sintent,
7271                        specificTypes != null ? specificTypes[i] : null,
7272                            flags, userId);
7273                    if (ri == null) {
7274                        continue;
7275                    }
7276                    if (ri == mResolveInfo) {
7277                        // ACK!  Must do something better with this.
7278                    }
7279                    ai = ri.activityInfo;
7280                    comp = new ComponentName(ai.applicationInfo.packageName,
7281                            ai.name);
7282                } else {
7283                    ai = getActivityInfo(comp, flags, userId);
7284                    if (ai == null) {
7285                        continue;
7286                    }
7287                }
7288
7289                // Look for any generic query activities that are duplicates
7290                // of this specific one, and remove them from the results.
7291                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7292                N = results.size();
7293                int j;
7294                for (j=specificsPos; j<N; j++) {
7295                    ResolveInfo sri = results.get(j);
7296                    if ((sri.activityInfo.name.equals(comp.getClassName())
7297                            && sri.activityInfo.applicationInfo.packageName.equals(
7298                                    comp.getPackageName()))
7299                        || (action != null && sri.filter.matchAction(action))) {
7300                        results.remove(j);
7301                        if (DEBUG_INTENT_MATCHING) Log.v(
7302                            TAG, "Removing duplicate item from " + j
7303                            + " due to specific " + specificsPos);
7304                        if (ri == null) {
7305                            ri = sri;
7306                        }
7307                        j--;
7308                        N--;
7309                    }
7310                }
7311
7312                // Add this specific item to its proper place.
7313                if (ri == null) {
7314                    ri = new ResolveInfo();
7315                    ri.activityInfo = ai;
7316                }
7317                results.add(specificsPos, ri);
7318                ri.specificIndex = i;
7319                specificsPos++;
7320            }
7321        }
7322
7323        // Now we go through the remaining generic results and remove any
7324        // duplicate actions that are found here.
7325        N = results.size();
7326        for (int i=specificsPos; i<N-1; i++) {
7327            final ResolveInfo rii = results.get(i);
7328            if (rii.filter == null) {
7329                continue;
7330            }
7331
7332            // Iterate over all of the actions of this result's intent
7333            // filter...  typically this should be just one.
7334            final Iterator<String> it = rii.filter.actionsIterator();
7335            if (it == null) {
7336                continue;
7337            }
7338            while (it.hasNext()) {
7339                final String action = it.next();
7340                if (resultsAction != null && resultsAction.equals(action)) {
7341                    // If this action was explicitly requested, then don't
7342                    // remove things that have it.
7343                    continue;
7344                }
7345                for (int j=i+1; j<N; j++) {
7346                    final ResolveInfo rij = results.get(j);
7347                    if (rij.filter != null && rij.filter.hasAction(action)) {
7348                        results.remove(j);
7349                        if (DEBUG_INTENT_MATCHING) Log.v(
7350                            TAG, "Removing duplicate item from " + j
7351                            + " due to action " + action + " at " + i);
7352                        j--;
7353                        N--;
7354                    }
7355                }
7356            }
7357
7358            // If the caller didn't request filter information, drop it now
7359            // so we don't have to marshall/unmarshall it.
7360            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7361                rii.filter = null;
7362            }
7363        }
7364
7365        // Filter out the caller activity if so requested.
7366        if (caller != null) {
7367            N = results.size();
7368            for (int i=0; i<N; i++) {
7369                ActivityInfo ainfo = results.get(i).activityInfo;
7370                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7371                        && caller.getClassName().equals(ainfo.name)) {
7372                    results.remove(i);
7373                    break;
7374                }
7375            }
7376        }
7377
7378        // If the caller didn't request filter information,
7379        // drop them now so we don't have to
7380        // marshall/unmarshall it.
7381        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7382            N = results.size();
7383            for (int i=0; i<N; i++) {
7384                results.get(i).filter = null;
7385            }
7386        }
7387
7388        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7389        return results;
7390    }
7391
7392    @Override
7393    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7394            String resolvedType, int flags, int userId) {
7395        return new ParceledListSlice<>(
7396                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7397                        false /*allowDynamicSplits*/));
7398    }
7399
7400    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7401            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7402        if (!sUserManager.exists(userId)) return Collections.emptyList();
7403        final int callingUid = Binder.getCallingUid();
7404        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7405                false /*requireFullPermission*/, false /*checkShell*/,
7406                "query intent receivers");
7407        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7408        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7409                false /*includeInstantApps*/);
7410        ComponentName comp = intent.getComponent();
7411        if (comp == null) {
7412            if (intent.getSelector() != null) {
7413                intent = intent.getSelector();
7414                comp = intent.getComponent();
7415            }
7416        }
7417        if (comp != null) {
7418            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7419            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7420            if (ai != null) {
7421                // When specifying an explicit component, we prevent the activity from being
7422                // used when either 1) the calling package is normal and the activity is within
7423                // an instant application or 2) the calling package is ephemeral and the
7424                // activity is not visible to instant applications.
7425                final boolean matchInstantApp =
7426                        (flags & PackageManager.MATCH_INSTANT) != 0;
7427                final boolean matchVisibleToInstantAppOnly =
7428                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7429                final boolean matchExplicitlyVisibleOnly =
7430                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7431                final boolean isCallerInstantApp =
7432                        instantAppPkgName != null;
7433                final boolean isTargetSameInstantApp =
7434                        comp.getPackageName().equals(instantAppPkgName);
7435                final boolean isTargetInstantApp =
7436                        (ai.applicationInfo.privateFlags
7437                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7438                final boolean isTargetVisibleToInstantApp =
7439                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7440                final boolean isTargetExplicitlyVisibleToInstantApp =
7441                        isTargetVisibleToInstantApp
7442                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7443                final boolean isTargetHiddenFromInstantApp =
7444                        !isTargetVisibleToInstantApp
7445                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7446                final boolean blockResolution =
7447                        !isTargetSameInstantApp
7448                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7449                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7450                                        && isTargetHiddenFromInstantApp));
7451                if (!blockResolution) {
7452                    ResolveInfo ri = new ResolveInfo();
7453                    ri.activityInfo = ai;
7454                    list.add(ri);
7455                }
7456            }
7457            return applyPostResolutionFilter(
7458                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7459        }
7460
7461        // reader
7462        synchronized (mPackages) {
7463            String pkgName = intent.getPackage();
7464            if (pkgName == null) {
7465                final List<ResolveInfo> result =
7466                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7467                return applyPostResolutionFilter(
7468                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7469            }
7470            final PackageParser.Package pkg = mPackages.get(pkgName);
7471            if (pkg != null) {
7472                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7473                        intent, resolvedType, flags, pkg.receivers, userId);
7474                return applyPostResolutionFilter(
7475                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7476            }
7477            return Collections.emptyList();
7478        }
7479    }
7480
7481    @Override
7482    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7483        final int callingUid = Binder.getCallingUid();
7484        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7485    }
7486
7487    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7488            int userId, int callingUid) {
7489        if (!sUserManager.exists(userId)) return null;
7490        flags = updateFlagsForResolve(
7491                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7492        List<ResolveInfo> query = queryIntentServicesInternal(
7493                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7494        if (query != null) {
7495            if (query.size() >= 1) {
7496                // If there is more than one service with the same priority,
7497                // just arbitrarily pick the first one.
7498                return query.get(0);
7499            }
7500        }
7501        return null;
7502    }
7503
7504    @Override
7505    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7506            String resolvedType, int flags, int userId) {
7507        final int callingUid = Binder.getCallingUid();
7508        return new ParceledListSlice<>(queryIntentServicesInternal(
7509                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7510    }
7511
7512    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7513            String resolvedType, int flags, int userId, int callingUid,
7514            boolean includeInstantApps) {
7515        if (!sUserManager.exists(userId)) return Collections.emptyList();
7516        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7517                false /*requireFullPermission*/, false /*checkShell*/,
7518                "query intent receivers");
7519        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7520        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7521        ComponentName comp = intent.getComponent();
7522        if (comp == null) {
7523            if (intent.getSelector() != null) {
7524                intent = intent.getSelector();
7525                comp = intent.getComponent();
7526            }
7527        }
7528        if (comp != null) {
7529            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7530            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7531            if (si != null) {
7532                // When specifying an explicit component, we prevent the service from being
7533                // used when either 1) the service is in an instant application and the
7534                // caller is not the same instant application or 2) the calling package is
7535                // ephemeral and the activity is not visible to ephemeral applications.
7536                final boolean matchInstantApp =
7537                        (flags & PackageManager.MATCH_INSTANT) != 0;
7538                final boolean matchVisibleToInstantAppOnly =
7539                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7540                final boolean isCallerInstantApp =
7541                        instantAppPkgName != null;
7542                final boolean isTargetSameInstantApp =
7543                        comp.getPackageName().equals(instantAppPkgName);
7544                final boolean isTargetInstantApp =
7545                        (si.applicationInfo.privateFlags
7546                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7547                final boolean isTargetHiddenFromInstantApp =
7548                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7549                final boolean blockResolution =
7550                        !isTargetSameInstantApp
7551                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7552                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7553                                        && isTargetHiddenFromInstantApp));
7554                if (!blockResolution) {
7555                    final ResolveInfo ri = new ResolveInfo();
7556                    ri.serviceInfo = si;
7557                    list.add(ri);
7558                }
7559            }
7560            return list;
7561        }
7562
7563        // reader
7564        synchronized (mPackages) {
7565            String pkgName = intent.getPackage();
7566            if (pkgName == null) {
7567                return applyPostServiceResolutionFilter(
7568                        mServices.queryIntent(intent, resolvedType, flags, userId),
7569                        instantAppPkgName);
7570            }
7571            final PackageParser.Package pkg = mPackages.get(pkgName);
7572            if (pkg != null) {
7573                return applyPostServiceResolutionFilter(
7574                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7575                                userId),
7576                        instantAppPkgName);
7577            }
7578            return Collections.emptyList();
7579        }
7580    }
7581
7582    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7583            String instantAppPkgName) {
7584        if (instantAppPkgName == null) {
7585            return resolveInfos;
7586        }
7587        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7588            final ResolveInfo info = resolveInfos.get(i);
7589            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7590            // allow services that are defined in the provided package
7591            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7592                if (info.serviceInfo.splitName != null
7593                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7594                                info.serviceInfo.splitName)) {
7595                    // requested service is defined in a split that hasn't been installed yet.
7596                    // add the installer to the resolve list
7597                    if (DEBUG_EPHEMERAL) {
7598                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7599                    }
7600                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7601                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7602                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7603                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
7604                            null /*failureIntent*/);
7605                    // make sure this resolver is the default
7606                    installerInfo.isDefault = true;
7607                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7608                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7609                    // add a non-generic filter
7610                    installerInfo.filter = new IntentFilter();
7611                    // load resources from the correct package
7612                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7613                    resolveInfos.set(i, installerInfo);
7614                }
7615                continue;
7616            }
7617            // allow services that have been explicitly exposed to ephemeral apps
7618            if (!isEphemeralApp
7619                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7620                continue;
7621            }
7622            resolveInfos.remove(i);
7623        }
7624        return resolveInfos;
7625    }
7626
7627    @Override
7628    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7629            String resolvedType, int flags, int userId) {
7630        return new ParceledListSlice<>(
7631                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7632    }
7633
7634    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7635            Intent intent, String resolvedType, int flags, int userId) {
7636        if (!sUserManager.exists(userId)) return Collections.emptyList();
7637        final int callingUid = Binder.getCallingUid();
7638        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7639        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7640                false /*includeInstantApps*/);
7641        ComponentName comp = intent.getComponent();
7642        if (comp == null) {
7643            if (intent.getSelector() != null) {
7644                intent = intent.getSelector();
7645                comp = intent.getComponent();
7646            }
7647        }
7648        if (comp != null) {
7649            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7650            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7651            if (pi != null) {
7652                // When specifying an explicit component, we prevent the provider from being
7653                // used when either 1) the provider is in an instant application and the
7654                // caller is not the same instant application or 2) the calling package is an
7655                // instant application and the provider is not visible to instant applications.
7656                final boolean matchInstantApp =
7657                        (flags & PackageManager.MATCH_INSTANT) != 0;
7658                final boolean matchVisibleToInstantAppOnly =
7659                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7660                final boolean isCallerInstantApp =
7661                        instantAppPkgName != null;
7662                final boolean isTargetSameInstantApp =
7663                        comp.getPackageName().equals(instantAppPkgName);
7664                final boolean isTargetInstantApp =
7665                        (pi.applicationInfo.privateFlags
7666                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7667                final boolean isTargetHiddenFromInstantApp =
7668                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7669                final boolean blockResolution =
7670                        !isTargetSameInstantApp
7671                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7672                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7673                                        && isTargetHiddenFromInstantApp));
7674                if (!blockResolution) {
7675                    final ResolveInfo ri = new ResolveInfo();
7676                    ri.providerInfo = pi;
7677                    list.add(ri);
7678                }
7679            }
7680            return list;
7681        }
7682
7683        // reader
7684        synchronized (mPackages) {
7685            String pkgName = intent.getPackage();
7686            if (pkgName == null) {
7687                return applyPostContentProviderResolutionFilter(
7688                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7689                        instantAppPkgName);
7690            }
7691            final PackageParser.Package pkg = mPackages.get(pkgName);
7692            if (pkg != null) {
7693                return applyPostContentProviderResolutionFilter(
7694                        mProviders.queryIntentForPackage(
7695                        intent, resolvedType, flags, pkg.providers, userId),
7696                        instantAppPkgName);
7697            }
7698            return Collections.emptyList();
7699        }
7700    }
7701
7702    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7703            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7704        if (instantAppPkgName == null) {
7705            return resolveInfos;
7706        }
7707        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7708            final ResolveInfo info = resolveInfos.get(i);
7709            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7710            // allow providers that are defined in the provided package
7711            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7712                if (info.providerInfo.splitName != null
7713                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7714                                info.providerInfo.splitName)) {
7715                    // requested provider is defined in a split that hasn't been installed yet.
7716                    // add the installer to the resolve list
7717                    if (DEBUG_EPHEMERAL) {
7718                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7719                    }
7720                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7721                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7722                            info.providerInfo.packageName, info.providerInfo.splitName,
7723                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
7724                            null /*failureIntent*/);
7725                    // make sure this resolver is the default
7726                    installerInfo.isDefault = true;
7727                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7728                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7729                    // add a non-generic filter
7730                    installerInfo.filter = new IntentFilter();
7731                    // load resources from the correct package
7732                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7733                    resolveInfos.set(i, installerInfo);
7734                }
7735                continue;
7736            }
7737            // allow providers that have been explicitly exposed to instant applications
7738            if (!isEphemeralApp
7739                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7740                continue;
7741            }
7742            resolveInfos.remove(i);
7743        }
7744        return resolveInfos;
7745    }
7746
7747    @Override
7748    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7749        final int callingUid = Binder.getCallingUid();
7750        if (getInstantAppPackageName(callingUid) != null) {
7751            return ParceledListSlice.emptyList();
7752        }
7753        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7754        flags = updateFlagsForPackage(flags, userId, null);
7755        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7756        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7757                true /* requireFullPermission */, false /* checkShell */,
7758                "get installed packages");
7759
7760        // writer
7761        synchronized (mPackages) {
7762            ArrayList<PackageInfo> list;
7763            if (listUninstalled) {
7764                list = new ArrayList<>(mSettings.mPackages.size());
7765                for (PackageSetting ps : mSettings.mPackages.values()) {
7766                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7767                        continue;
7768                    }
7769                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7770                        continue;
7771                    }
7772                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7773                    if (pi != null) {
7774                        list.add(pi);
7775                    }
7776                }
7777            } else {
7778                list = new ArrayList<>(mPackages.size());
7779                for (PackageParser.Package p : mPackages.values()) {
7780                    final PackageSetting ps = (PackageSetting) p.mExtras;
7781                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7782                        continue;
7783                    }
7784                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7785                        continue;
7786                    }
7787                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7788                            p.mExtras, flags, userId);
7789                    if (pi != null) {
7790                        list.add(pi);
7791                    }
7792                }
7793            }
7794
7795            return new ParceledListSlice<>(list);
7796        }
7797    }
7798
7799    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7800            String[] permissions, boolean[] tmp, int flags, int userId) {
7801        int numMatch = 0;
7802        final PermissionsState permissionsState = ps.getPermissionsState();
7803        for (int i=0; i<permissions.length; i++) {
7804            final String permission = permissions[i];
7805            if (permissionsState.hasPermission(permission, userId)) {
7806                tmp[i] = true;
7807                numMatch++;
7808            } else {
7809                tmp[i] = false;
7810            }
7811        }
7812        if (numMatch == 0) {
7813            return;
7814        }
7815        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7816
7817        // The above might return null in cases of uninstalled apps or install-state
7818        // skew across users/profiles.
7819        if (pi != null) {
7820            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7821                if (numMatch == permissions.length) {
7822                    pi.requestedPermissions = permissions;
7823                } else {
7824                    pi.requestedPermissions = new String[numMatch];
7825                    numMatch = 0;
7826                    for (int i=0; i<permissions.length; i++) {
7827                        if (tmp[i]) {
7828                            pi.requestedPermissions[numMatch] = permissions[i];
7829                            numMatch++;
7830                        }
7831                    }
7832                }
7833            }
7834            list.add(pi);
7835        }
7836    }
7837
7838    @Override
7839    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7840            String[] permissions, int flags, int userId) {
7841        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7842        flags = updateFlagsForPackage(flags, userId, permissions);
7843        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7844                true /* requireFullPermission */, false /* checkShell */,
7845                "get packages holding permissions");
7846        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7847
7848        // writer
7849        synchronized (mPackages) {
7850            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7851            boolean[] tmpBools = new boolean[permissions.length];
7852            if (listUninstalled) {
7853                for (PackageSetting ps : mSettings.mPackages.values()) {
7854                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7855                            userId);
7856                }
7857            } else {
7858                for (PackageParser.Package pkg : mPackages.values()) {
7859                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7860                    if (ps != null) {
7861                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7862                                userId);
7863                    }
7864                }
7865            }
7866
7867            return new ParceledListSlice<PackageInfo>(list);
7868        }
7869    }
7870
7871    @Override
7872    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7873        final int callingUid = Binder.getCallingUid();
7874        if (getInstantAppPackageName(callingUid) != null) {
7875            return ParceledListSlice.emptyList();
7876        }
7877        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7878        flags = updateFlagsForApplication(flags, userId, null);
7879        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7880
7881        // writer
7882        synchronized (mPackages) {
7883            ArrayList<ApplicationInfo> list;
7884            if (listUninstalled) {
7885                list = new ArrayList<>(mSettings.mPackages.size());
7886                for (PackageSetting ps : mSettings.mPackages.values()) {
7887                    ApplicationInfo ai;
7888                    int effectiveFlags = flags;
7889                    if (ps.isSystem()) {
7890                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7891                    }
7892                    if (ps.pkg != null) {
7893                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7894                            continue;
7895                        }
7896                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7897                            continue;
7898                        }
7899                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7900                                ps.readUserState(userId), userId);
7901                        if (ai != null) {
7902                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7903                        }
7904                    } else {
7905                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7906                        // and already converts to externally visible package name
7907                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7908                                callingUid, effectiveFlags, userId);
7909                    }
7910                    if (ai != null) {
7911                        list.add(ai);
7912                    }
7913                }
7914            } else {
7915                list = new ArrayList<>(mPackages.size());
7916                for (PackageParser.Package p : mPackages.values()) {
7917                    if (p.mExtras != null) {
7918                        PackageSetting ps = (PackageSetting) p.mExtras;
7919                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7920                            continue;
7921                        }
7922                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7923                            continue;
7924                        }
7925                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7926                                ps.readUserState(userId), userId);
7927                        if (ai != null) {
7928                            ai.packageName = resolveExternalPackageNameLPr(p);
7929                            list.add(ai);
7930                        }
7931                    }
7932                }
7933            }
7934
7935            return new ParceledListSlice<>(list);
7936        }
7937    }
7938
7939    @Override
7940    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7941        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7942            return null;
7943        }
7944        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7945            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7946                    "getEphemeralApplications");
7947        }
7948        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7949                true /* requireFullPermission */, false /* checkShell */,
7950                "getEphemeralApplications");
7951        synchronized (mPackages) {
7952            List<InstantAppInfo> instantApps = mInstantAppRegistry
7953                    .getInstantAppsLPr(userId);
7954            if (instantApps != null) {
7955                return new ParceledListSlice<>(instantApps);
7956            }
7957        }
7958        return null;
7959    }
7960
7961    @Override
7962    public boolean isInstantApp(String packageName, int userId) {
7963        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7964                true /* requireFullPermission */, false /* checkShell */,
7965                "isInstantApp");
7966        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7967            return false;
7968        }
7969
7970        synchronized (mPackages) {
7971            int callingUid = Binder.getCallingUid();
7972            if (Process.isIsolated(callingUid)) {
7973                callingUid = mIsolatedOwners.get(callingUid);
7974            }
7975            final PackageSetting ps = mSettings.mPackages.get(packageName);
7976            PackageParser.Package pkg = mPackages.get(packageName);
7977            final boolean returnAllowed =
7978                    ps != null
7979                    && (isCallerSameApp(packageName, callingUid)
7980                            || canViewInstantApps(callingUid, userId)
7981                            || mInstantAppRegistry.isInstantAccessGranted(
7982                                    userId, UserHandle.getAppId(callingUid), ps.appId));
7983            if (returnAllowed) {
7984                return ps.getInstantApp(userId);
7985            }
7986        }
7987        return false;
7988    }
7989
7990    @Override
7991    public byte[] getInstantAppCookie(String packageName, int userId) {
7992        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7993            return null;
7994        }
7995
7996        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7997                true /* requireFullPermission */, false /* checkShell */,
7998                "getInstantAppCookie");
7999        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8000            return null;
8001        }
8002        synchronized (mPackages) {
8003            return mInstantAppRegistry.getInstantAppCookieLPw(
8004                    packageName, userId);
8005        }
8006    }
8007
8008    @Override
8009    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8010        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8011            return true;
8012        }
8013
8014        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8015                true /* requireFullPermission */, true /* checkShell */,
8016                "setInstantAppCookie");
8017        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8018            return false;
8019        }
8020        synchronized (mPackages) {
8021            return mInstantAppRegistry.setInstantAppCookieLPw(
8022                    packageName, cookie, userId);
8023        }
8024    }
8025
8026    @Override
8027    public Bitmap getInstantAppIcon(String packageName, int userId) {
8028        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8029            return null;
8030        }
8031
8032        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8033            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8034                    "getInstantAppIcon");
8035        }
8036        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8037                true /* requireFullPermission */, false /* checkShell */,
8038                "getInstantAppIcon");
8039
8040        synchronized (mPackages) {
8041            return mInstantAppRegistry.getInstantAppIconLPw(
8042                    packageName, userId);
8043        }
8044    }
8045
8046    private boolean isCallerSameApp(String packageName, int uid) {
8047        PackageParser.Package pkg = mPackages.get(packageName);
8048        return pkg != null
8049                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8050    }
8051
8052    @Override
8053    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8054        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8055            return ParceledListSlice.emptyList();
8056        }
8057        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8058    }
8059
8060    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8061        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8062
8063        // reader
8064        synchronized (mPackages) {
8065            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8066            final int userId = UserHandle.getCallingUserId();
8067            while (i.hasNext()) {
8068                final PackageParser.Package p = i.next();
8069                if (p.applicationInfo == null) continue;
8070
8071                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8072                        && !p.applicationInfo.isDirectBootAware();
8073                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8074                        && p.applicationInfo.isDirectBootAware();
8075
8076                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8077                        && (!mSafeMode || isSystemApp(p))
8078                        && (matchesUnaware || matchesAware)) {
8079                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8080                    if (ps != null) {
8081                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8082                                ps.readUserState(userId), userId);
8083                        if (ai != null) {
8084                            finalList.add(ai);
8085                        }
8086                    }
8087                }
8088            }
8089        }
8090
8091        return finalList;
8092    }
8093
8094    @Override
8095    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8096        return resolveContentProviderInternal(name, flags, userId);
8097    }
8098
8099    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8100        if (!sUserManager.exists(userId)) return null;
8101        flags = updateFlagsForComponent(flags, userId, name);
8102        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8103        // reader
8104        synchronized (mPackages) {
8105            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8106            PackageSetting ps = provider != null
8107                    ? mSettings.mPackages.get(provider.owner.packageName)
8108                    : null;
8109            if (ps != null) {
8110                final boolean isInstantApp = ps.getInstantApp(userId);
8111                // normal application; filter out instant application provider
8112                if (instantAppPkgName == null && isInstantApp) {
8113                    return null;
8114                }
8115                // instant application; filter out other instant applications
8116                if (instantAppPkgName != null
8117                        && isInstantApp
8118                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8119                    return null;
8120                }
8121                // instant application; filter out non-exposed provider
8122                if (instantAppPkgName != null
8123                        && !isInstantApp
8124                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8125                    return null;
8126                }
8127                // provider not enabled
8128                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8129                    return null;
8130                }
8131                return PackageParser.generateProviderInfo(
8132                        provider, flags, ps.readUserState(userId), userId);
8133            }
8134            return null;
8135        }
8136    }
8137
8138    /**
8139     * @deprecated
8140     */
8141    @Deprecated
8142    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8143        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8144            return;
8145        }
8146        // reader
8147        synchronized (mPackages) {
8148            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8149                    .entrySet().iterator();
8150            final int userId = UserHandle.getCallingUserId();
8151            while (i.hasNext()) {
8152                Map.Entry<String, PackageParser.Provider> entry = i.next();
8153                PackageParser.Provider p = entry.getValue();
8154                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8155
8156                if (ps != null && p.syncable
8157                        && (!mSafeMode || (p.info.applicationInfo.flags
8158                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8159                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8160                            ps.readUserState(userId), userId);
8161                    if (info != null) {
8162                        outNames.add(entry.getKey());
8163                        outInfo.add(info);
8164                    }
8165                }
8166            }
8167        }
8168    }
8169
8170    @Override
8171    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8172            int uid, int flags, String metaDataKey) {
8173        final int callingUid = Binder.getCallingUid();
8174        final int userId = processName != null ? UserHandle.getUserId(uid)
8175                : UserHandle.getCallingUserId();
8176        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8177        flags = updateFlagsForComponent(flags, userId, processName);
8178        ArrayList<ProviderInfo> finalList = null;
8179        // reader
8180        synchronized (mPackages) {
8181            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8182            while (i.hasNext()) {
8183                final PackageParser.Provider p = i.next();
8184                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8185                if (ps != null && p.info.authority != null
8186                        && (processName == null
8187                                || (p.info.processName.equals(processName)
8188                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8189                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8190
8191                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8192                    // parameter.
8193                    if (metaDataKey != null
8194                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8195                        continue;
8196                    }
8197                    final ComponentName component =
8198                            new ComponentName(p.info.packageName, p.info.name);
8199                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8200                        continue;
8201                    }
8202                    if (finalList == null) {
8203                        finalList = new ArrayList<ProviderInfo>(3);
8204                    }
8205                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8206                            ps.readUserState(userId), userId);
8207                    if (info != null) {
8208                        finalList.add(info);
8209                    }
8210                }
8211            }
8212        }
8213
8214        if (finalList != null) {
8215            Collections.sort(finalList, mProviderInitOrderSorter);
8216            return new ParceledListSlice<ProviderInfo>(finalList);
8217        }
8218
8219        return ParceledListSlice.emptyList();
8220    }
8221
8222    @Override
8223    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8224        // reader
8225        synchronized (mPackages) {
8226            final int callingUid = Binder.getCallingUid();
8227            final int callingUserId = UserHandle.getUserId(callingUid);
8228            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8229            if (ps == null) return null;
8230            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8231                return null;
8232            }
8233            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8234            return PackageParser.generateInstrumentationInfo(i, flags);
8235        }
8236    }
8237
8238    @Override
8239    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8240            String targetPackage, int flags) {
8241        final int callingUid = Binder.getCallingUid();
8242        final int callingUserId = UserHandle.getUserId(callingUid);
8243        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8244        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8245            return ParceledListSlice.emptyList();
8246        }
8247        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8248    }
8249
8250    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8251            int flags) {
8252        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8253
8254        // reader
8255        synchronized (mPackages) {
8256            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8257            while (i.hasNext()) {
8258                final PackageParser.Instrumentation p = i.next();
8259                if (targetPackage == null
8260                        || targetPackage.equals(p.info.targetPackage)) {
8261                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8262                            flags);
8263                    if (ii != null) {
8264                        finalList.add(ii);
8265                    }
8266                }
8267            }
8268        }
8269
8270        return finalList;
8271    }
8272
8273    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8274        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8275        try {
8276            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8277        } finally {
8278            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8279        }
8280    }
8281
8282    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8283        final File[] files = scanDir.listFiles();
8284        if (ArrayUtils.isEmpty(files)) {
8285            Log.d(TAG, "No files in app dir " + scanDir);
8286            return;
8287        }
8288
8289        if (DEBUG_PACKAGE_SCANNING) {
8290            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8291                    + " flags=0x" + Integer.toHexString(parseFlags));
8292        }
8293        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8294                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8295                mParallelPackageParserCallback)) {
8296            // Submit files for parsing in parallel
8297            int fileCount = 0;
8298            for (File file : files) {
8299                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8300                        && !PackageInstallerService.isStageName(file.getName());
8301                if (!isPackage) {
8302                    // Ignore entries which are not packages
8303                    continue;
8304                }
8305                parallelPackageParser.submit(file, parseFlags);
8306                fileCount++;
8307            }
8308
8309            // Process results one by one
8310            for (; fileCount > 0; fileCount--) {
8311                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8312                Throwable throwable = parseResult.throwable;
8313                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8314
8315                if (throwable == null) {
8316                    // TODO(toddke): move lower in the scan chain
8317                    // Static shared libraries have synthetic package names
8318                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8319                        renameStaticSharedLibraryPackage(parseResult.pkg);
8320                    }
8321                    try {
8322                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8323                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8324                                    currentTime, null);
8325                        }
8326                    } catch (PackageManagerException e) {
8327                        errorCode = e.error;
8328                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8329                    }
8330                } else if (throwable instanceof PackageParser.PackageParserException) {
8331                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8332                            throwable;
8333                    errorCode = e.error;
8334                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8335                } else {
8336                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8337                            + parseResult.scanFile, throwable);
8338                }
8339
8340                // Delete invalid userdata apps
8341                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8342                        errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8343                    logCriticalInfo(Log.WARN,
8344                            "Deleting invalid package at " + parseResult.scanFile);
8345                    removeCodePathLI(parseResult.scanFile);
8346                }
8347            }
8348        }
8349    }
8350
8351    public static void reportSettingsProblem(int priority, String msg) {
8352        logCriticalInfo(priority, msg);
8353    }
8354
8355    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8356            boolean forceCollect, boolean skipVerify) throws PackageManagerException {
8357        // When upgrading from pre-N MR1, verify the package time stamp using the package
8358        // directory and not the APK file.
8359        final long lastModifiedTime = mIsPreNMR1Upgrade
8360                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8361        if (ps != null && !forceCollect
8362                && ps.codePathString.equals(pkg.codePath)
8363                && ps.timeStamp == lastModifiedTime
8364                && !isCompatSignatureUpdateNeeded(pkg)
8365                && !isRecoverSignatureUpdateNeeded(pkg)) {
8366            if (ps.signatures.mSigningDetails.signatures != null
8367                    && ps.signatures.mSigningDetails.signatures.length != 0
8368                    && ps.signatures.mSigningDetails.signatureSchemeVersion
8369                            != SignatureSchemeVersion.UNKNOWN) {
8370                // Optimization: reuse the existing cached signing data
8371                // if the package appears to be unchanged.
8372                pkg.mSigningDetails =
8373                        new PackageParser.SigningDetails(ps.signatures.mSigningDetails);
8374                return;
8375            }
8376
8377            Slog.w(TAG, "PackageSetting for " + ps.name
8378                    + " is missing signatures.  Collecting certs again to recover them.");
8379        } else {
8380            Slog.i(TAG, pkg.codePath + " changed; collecting certs" +
8381                    (forceCollect ? " (forced)" : ""));
8382        }
8383
8384        try {
8385            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8386            PackageParser.collectCertificates(pkg, skipVerify);
8387        } catch (PackageParserException e) {
8388            throw PackageManagerException.from(e);
8389        } finally {
8390            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8391        }
8392    }
8393
8394    /**
8395     *  Traces a package scan.
8396     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8397     */
8398    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8399            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8400        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8401        try {
8402            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8403        } finally {
8404            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8405        }
8406    }
8407
8408    /**
8409     *  Scans a package and returns the newly parsed package.
8410     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8411     */
8412    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8413            long currentTime, UserHandle user) throws PackageManagerException {
8414        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8415        PackageParser pp = new PackageParser();
8416        pp.setSeparateProcesses(mSeparateProcesses);
8417        pp.setOnlyCoreApps(mOnlyCore);
8418        pp.setDisplayMetrics(mMetrics);
8419        pp.setCallback(mPackageParserCallback);
8420
8421        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8422        final PackageParser.Package pkg;
8423        try {
8424            pkg = pp.parsePackage(scanFile, parseFlags);
8425        } catch (PackageParserException e) {
8426            throw PackageManagerException.from(e);
8427        } finally {
8428            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8429        }
8430
8431        // Static shared libraries have synthetic package names
8432        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8433            renameStaticSharedLibraryPackage(pkg);
8434        }
8435
8436        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8437    }
8438
8439    /**
8440     *  Scans a package and returns the newly parsed package.
8441     *  @throws PackageManagerException on a parse error.
8442     */
8443    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8444            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8445            @Nullable UserHandle user)
8446                    throws PackageManagerException {
8447        // If the package has children and this is the first dive in the function
8448        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8449        // packages (parent and children) would be successfully scanned before the
8450        // actual scan since scanning mutates internal state and we want to atomically
8451        // install the package and its children.
8452        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8453            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8454                scanFlags |= SCAN_CHECK_ONLY;
8455            }
8456        } else {
8457            scanFlags &= ~SCAN_CHECK_ONLY;
8458        }
8459
8460        // Scan the parent
8461        PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags,
8462                scanFlags, currentTime, user);
8463
8464        // Scan the children
8465        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8466        for (int i = 0; i < childCount; i++) {
8467            PackageParser.Package childPackage = pkg.childPackages.get(i);
8468            addForInitLI(childPackage, parseFlags, scanFlags,
8469                    currentTime, user);
8470        }
8471
8472
8473        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8474            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8475        }
8476
8477        return scannedPkg;
8478    }
8479
8480    /**
8481     * Returns if full apk verification can be skipped for the whole package, including the splits.
8482     */
8483    private boolean canSkipFullPackageVerification(PackageParser.Package pkg) {
8484        if (!canSkipFullApkVerification(pkg.baseCodePath)) {
8485            return false;
8486        }
8487        // TODO: Allow base and splits to be verified individually.
8488        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8489            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8490                if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) {
8491                    return false;
8492                }
8493            }
8494        }
8495        return true;
8496    }
8497
8498    /**
8499     * Returns if full apk verification can be skipped, depending on current FSVerity setup and
8500     * whether the apk contains signed root hash.  Note that the signer's certificate still needs to
8501     * match one in a trusted source, and should be done separately.
8502     */
8503    private boolean canSkipFullApkVerification(String apkPath) {
8504        byte[] rootHashObserved = null;
8505        try {
8506            rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath);
8507            if (rootHashObserved == null) {
8508                return false;  // APK does not contain Merkle tree root hash.
8509            }
8510            synchronized (mInstallLock) {
8511                // Returns whether the observed root hash matches what kernel has.
8512                mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved);
8513                return true;
8514            }
8515        } catch (InstallerException | IOException | DigestException |
8516                NoSuchAlgorithmException e) {
8517            Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e);
8518        }
8519        return false;
8520    }
8521
8522    // Temporary to catch potential issues with refactoring
8523    private static boolean REFACTOR_DEBUG = true;
8524    /**
8525     * Adds a new package to the internal data structures during platform initialization.
8526     * <p>After adding, the package is known to the system and available for querying.
8527     * <p>For packages located on the device ROM [eg. packages located in /system, /vendor,
8528     * etc...], additional checks are performed. Basic verification [such as ensuring
8529     * matching signatures, checking version codes, etc...] occurs if the package is
8530     * identical to a previously known package. If the package fails a signature check,
8531     * the version installed on /data will be removed. If the version of the new package
8532     * is less than or equal than the version on /data, it will be ignored.
8533     * <p>Regardless of the package location, the results are applied to the internal
8534     * structures and the package is made available to the rest of the system.
8535     * <p>NOTE: The return value should be removed. It's the passed in package object.
8536     */
8537    private PackageParser.Package addForInitLI(PackageParser.Package pkg,
8538            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8539            @Nullable UserHandle user)
8540                    throws PackageManagerException {
8541        final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0;
8542        final String renamedPkgName;
8543        final PackageSetting disabledPkgSetting;
8544        final boolean isSystemPkgUpdated;
8545        final boolean pkgAlreadyExists;
8546        PackageSetting pkgSetting;
8547
8548        // NOTE: installPackageLI() has the same code to setup the package's
8549        // application info. This probably should be done lower in the call
8550        // stack [such as scanPackageOnly()]. However, we verify the application
8551        // info prior to that [in scanPackageNew()] and thus have to setup
8552        // the application info early.
8553        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8554        pkg.setApplicationInfoCodePath(pkg.codePath);
8555        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8556        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8557        pkg.setApplicationInfoResourcePath(pkg.codePath);
8558        pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
8559        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8560
8561        synchronized (mPackages) {
8562            renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8563            final String realPkgName = getRealPackageName(pkg, renamedPkgName);
8564if (REFACTOR_DEBUG) {
8565Slog.e("TODD",
8566        "Add pkg: " + pkg.packageName + (realPkgName==null?"":", realName: " + realPkgName));
8567}
8568            if (realPkgName != null) {
8569                ensurePackageRenamed(pkg, renamedPkgName);
8570            }
8571            final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
8572            final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName);
8573            pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting;
8574            pkgAlreadyExists = pkgSetting != null;
8575            final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName;
8576            disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName);
8577            isSystemPkgUpdated = disabledPkgSetting != null;
8578
8579            if (DEBUG_INSTALL && isSystemPkgUpdated) {
8580                Slog.d(TAG, "updatedPkg = " + disabledPkgSetting);
8581            }
8582if (REFACTOR_DEBUG) {
8583Slog.e("TODD",
8584        "SSP? " + scanSystemPartition
8585        + ", exists? " + pkgAlreadyExists + (pkgAlreadyExists?" "+pkgSetting.toString():"")
8586        + ", upgraded? " + isSystemPkgUpdated + (isSystemPkgUpdated?" "+disabledPkgSetting.toString():""));
8587}
8588
8589            final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null)
8590                    ? mSettings.getSharedUserLPw(pkg.mSharedUserId,
8591                            0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true)
8592                    : null;
8593            if (DEBUG_PACKAGE_SCANNING
8594                    && (parseFlags & PackageParser.PARSE_CHATTY) != 0
8595                    && sharedUserSetting != null) {
8596                Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
8597                        + " (uid=" + sharedUserSetting.userId + "):"
8598                        + " packages=" + sharedUserSetting.packages);
8599if (REFACTOR_DEBUG) {
8600Slog.e("TODD",
8601        "Shared UserID " + pkg.mSharedUserId
8602        + " (uid=" + sharedUserSetting.userId + "):"
8603        + " packages=" + sharedUserSetting.packages);
8604}
8605            }
8606
8607            if (scanSystemPartition) {
8608                // Potentially prune child packages. If the application on the /system
8609                // partition has been updated via OTA, but, is still disabled by a
8610                // version on /data, cycle through all of its children packages and
8611                // remove children that are no longer defined.
8612                if (isSystemPkgUpdated) {
8613if (REFACTOR_DEBUG) {
8614Slog.e("TODD",
8615        "Disable child packages");
8616}
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)) {
8628if (REFACTOR_DEBUG) {
8629Slog.e("TODD",
8630        "Ignore " + disabledChildPackageName);
8631}
8632                                disabledPackageAvailable = true;
8633                                break;
8634                            }
8635                        }
8636                        if (!disabledPackageAvailable) {
8637if (REFACTOR_DEBUG) {
8638Slog.e("TODD",
8639        "Disable " + disabledChildPackageName);
8640}
8641                            mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8642                        }
8643                    }
8644                    // we're updating the disabled package, so, scan it as the package setting
8645                    final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
8646                            disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */,
8647                            null /* originalPkgSetting */, null, parseFlags, scanFlags,
8648                            (pkg == mPlatformPackage), user);
8649if (REFACTOR_DEBUG) {
8650Slog.e("TODD",
8651        "Scan disabled system package");
8652Slog.e("TODD",
8653        "Pre: " + request.pkgSetting.dumpState_temp());
8654}
8655final ScanResult result =
8656                    scanPackageOnlyLI(request, mFactoryTest, -1L);
8657if (REFACTOR_DEBUG) {
8658Slog.e("TODD",
8659        "Post: " + (result.success?result.pkgSetting.dumpState_temp():"FAILED scan"));
8660}
8661                }
8662            }
8663        }
8664
8665        final boolean newPkgChangedPaths =
8666                pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath);
8667if (REFACTOR_DEBUG) {
8668Slog.e("TODD",
8669        "paths changed? " + newPkgChangedPaths
8670        + "; old: " + pkg.codePath
8671        + ", new: " + (pkgSetting==null?"<<NULL>>":pkgSetting.codePathString));
8672}
8673        final boolean newPkgVersionGreater =
8674                pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode;
8675if (REFACTOR_DEBUG) {
8676Slog.e("TODD",
8677        "version greater? " + newPkgVersionGreater
8678        + "; old: " + pkg.getLongVersionCode()
8679        + ", new: " + (pkgSetting==null?"<<NULL>>":pkgSetting.versionCode));
8680}
8681        final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated
8682                && newPkgChangedPaths && newPkgVersionGreater;
8683if (REFACTOR_DEBUG) {
8684    Slog.e("TODD",
8685            "system better? " + isSystemPkgBetter);
8686}
8687        if (isSystemPkgBetter) {
8688            // The version of the application on /system is greater than the version on
8689            // /data. Switch back to the application on /system.
8690            // It's safe to assume the application on /system will correctly scan. If not,
8691            // there won't be a working copy of the application.
8692            synchronized (mPackages) {
8693                // just remove the loaded entries from package lists
8694                mPackages.remove(pkgSetting.name);
8695            }
8696
8697            logCriticalInfo(Log.WARN,
8698                    "System package updated;"
8699                    + " name: " + pkgSetting.name
8700                    + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8701                    + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8702if (REFACTOR_DEBUG) {
8703Slog.e("TODD",
8704        "System package changed;"
8705        + " name: " + pkgSetting.name
8706        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8707        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8708}
8709
8710            final InstallArgs args = createInstallArgsForExisting(
8711                    packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8712                    pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8713            args.cleanUpResourcesLI();
8714            synchronized (mPackages) {
8715                mSettings.enableSystemPackageLPw(pkgSetting.name);
8716            }
8717        }
8718
8719        if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) {
8720if (REFACTOR_DEBUG) {
8721Slog.e("TODD",
8722        "THROW exception; system pkg version not good enough");
8723}
8724            // The version of the application on the /system partition is less than or
8725            // equal to the version on the /data partition. Throw an exception and use
8726            // the application already installed on the /data partition.
8727            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8728                    + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode
8729                    + " better than this " + pkg.getLongVersionCode());
8730        }
8731
8732        // Verify certificates against what was last scanned. If it is an updated priv app, we will
8733        // force re-collecting certificate.
8734        final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced(
8735                disabledPkgSetting);
8736        // Full APK verification can be skipped during certificate collection, only if the file is
8737        // in verified partition, or can be verified on access (when apk verity is enabled). In both
8738        // cases, only data in Signing Block is verified instead of the whole file.
8739        final boolean skipVerify = ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) ||
8740                (forceCollect && canSkipFullPackageVerification(pkg));
8741        collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify);
8742
8743        boolean shouldHideSystemApp = false;
8744        // A new application appeared on /system, but, we already have a copy of
8745        // the application installed on /data.
8746        if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists
8747                && !pkgSetting.isSystem()) {
8748            // if the signatures don't match, wipe the installed application and its data
8749            if (compareSignatures(pkgSetting.signatures.mSigningDetails.signatures,
8750                    pkg.mSigningDetails.signatures)
8751                            != PackageManager.SIGNATURE_MATCH) {
8752                logCriticalInfo(Log.WARN,
8753                        "System package signature mismatch;"
8754                        + " name: " + pkgSetting.name);
8755if (REFACTOR_DEBUG) {
8756Slog.e("TODD",
8757        "System package signature mismatch;"
8758        + " name: " + pkgSetting.name);
8759}
8760                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8761                        "scanPackageInternalLI")) {
8762                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8763                }
8764                pkgSetting = null;
8765            } else if (newPkgVersionGreater) {
8766                // The application on /system is newer than the application on /data.
8767                // Simply remove the application on /data [keeping application data]
8768                // and replace it with the version on /system.
8769                logCriticalInfo(Log.WARN,
8770                        "System package enabled;"
8771                        + " name: " + pkgSetting.name
8772                        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8773                        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8774if (REFACTOR_DEBUG) {
8775Slog.e("TODD",
8776        "System package enabled;"
8777        + " name: " + pkgSetting.name
8778        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8779        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8780}
8781                InstallArgs args = createInstallArgsForExisting(
8782                        packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8783                        pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8784                synchronized (mInstallLock) {
8785                    args.cleanUpResourcesLI();
8786                }
8787            } else {
8788                // The application on /system is older than the application on /data. Hide
8789                // the application on /system and the version on /data will be scanned later
8790                // and re-added like an update.
8791                shouldHideSystemApp = true;
8792                logCriticalInfo(Log.INFO,
8793                        "System package disabled;"
8794                        + " name: " + pkgSetting.name
8795                        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8796                        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8797if (REFACTOR_DEBUG) {
8798Slog.e("TODD",
8799        "System package disabled;"
8800        + " name: " + pkgSetting.name
8801        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8802        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8803}
8804            }
8805        }
8806
8807if (REFACTOR_DEBUG) {
8808Slog.e("TODD",
8809        "Scan package");
8810Slog.e("TODD",
8811        "Pre: " + (pkgSetting==null?"<<NONE>>":pkgSetting.dumpState_temp()));
8812}
8813        final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8814                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8815if (REFACTOR_DEBUG) {
8816pkgSetting = mSettings.getPackageLPr(pkg.packageName);
8817Slog.e("TODD",
8818        "Post: " + (pkgSetting==null?"<<NONE>>":pkgSetting.dumpState_temp()));
8819}
8820
8821        if (shouldHideSystemApp) {
8822if (REFACTOR_DEBUG) {
8823Slog.e("TODD",
8824        "Disable package: " + pkg.packageName);
8825}
8826            synchronized (mPackages) {
8827                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8828            }
8829        }
8830        return scannedPkg;
8831    }
8832
8833    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8834        // Derive the new package synthetic package name
8835        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8836                + pkg.staticSharedLibVersion);
8837    }
8838
8839    private static String fixProcessName(String defProcessName,
8840            String processName) {
8841        if (processName == null) {
8842            return defProcessName;
8843        }
8844        return processName;
8845    }
8846
8847    /**
8848     * Enforces that only the system UID or root's UID can call a method exposed
8849     * via Binder.
8850     *
8851     * @param message used as message if SecurityException is thrown
8852     * @throws SecurityException if the caller is not system or root
8853     */
8854    private static final void enforceSystemOrRoot(String message) {
8855        final int uid = Binder.getCallingUid();
8856        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8857            throw new SecurityException(message);
8858        }
8859    }
8860
8861    @Override
8862    public void performFstrimIfNeeded() {
8863        enforceSystemOrRoot("Only the system can request fstrim");
8864
8865        // Before everything else, see whether we need to fstrim.
8866        try {
8867            IStorageManager sm = PackageHelper.getStorageManager();
8868            if (sm != null) {
8869                boolean doTrim = false;
8870                final long interval = android.provider.Settings.Global.getLong(
8871                        mContext.getContentResolver(),
8872                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8873                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8874                if (interval > 0) {
8875                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8876                    if (timeSinceLast > interval) {
8877                        doTrim = true;
8878                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8879                                + "; running immediately");
8880                    }
8881                }
8882                if (doTrim) {
8883                    final boolean dexOptDialogShown;
8884                    synchronized (mPackages) {
8885                        dexOptDialogShown = mDexOptDialogShown;
8886                    }
8887                    if (!isFirstBoot() && dexOptDialogShown) {
8888                        try {
8889                            ActivityManager.getService().showBootMessage(
8890                                    mContext.getResources().getString(
8891                                            R.string.android_upgrading_fstrim), true);
8892                        } catch (RemoteException e) {
8893                        }
8894                    }
8895                    sm.runMaintenance();
8896                }
8897            } else {
8898                Slog.e(TAG, "storageManager service unavailable!");
8899            }
8900        } catch (RemoteException e) {
8901            // Can't happen; StorageManagerService is local
8902        }
8903    }
8904
8905    @Override
8906    public void updatePackagesIfNeeded() {
8907        enforceSystemOrRoot("Only the system can request package update");
8908
8909        // We need to re-extract after an OTA.
8910        boolean causeUpgrade = isUpgrade();
8911
8912        // First boot or factory reset.
8913        // Note: we also handle devices that are upgrading to N right now as if it is their
8914        //       first boot, as they do not have profile data.
8915        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8916
8917        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8918        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8919
8920        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8921            return;
8922        }
8923
8924        List<PackageParser.Package> pkgs;
8925        synchronized (mPackages) {
8926            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8927        }
8928
8929        final long startTime = System.nanoTime();
8930        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8931                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
8932                    false /* bootComplete */);
8933
8934        final int elapsedTimeSeconds =
8935                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8936
8937        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8938        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8939        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8940        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8941        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8942    }
8943
8944    /*
8945     * Return the prebuilt profile path given a package base code path.
8946     */
8947    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8948        return pkg.baseCodePath + ".prof";
8949    }
8950
8951    /**
8952     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8953     * containing statistics about the invocation. The array consists of three elements,
8954     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8955     * and {@code numberOfPackagesFailed}.
8956     */
8957    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8958            final String compilerFilter, boolean bootComplete) {
8959
8960        int numberOfPackagesVisited = 0;
8961        int numberOfPackagesOptimized = 0;
8962        int numberOfPackagesSkipped = 0;
8963        int numberOfPackagesFailed = 0;
8964        final int numberOfPackagesToDexopt = pkgs.size();
8965
8966        for (PackageParser.Package pkg : pkgs) {
8967            numberOfPackagesVisited++;
8968
8969            boolean useProfileForDexopt = false;
8970
8971            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8972                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8973                // that are already compiled.
8974                File profileFile = new File(getPrebuildProfilePath(pkg));
8975                // Copy profile if it exists.
8976                if (profileFile.exists()) {
8977                    try {
8978                        // We could also do this lazily before calling dexopt in
8979                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8980                        // is that we don't have a good way to say "do this only once".
8981                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8982                                pkg.applicationInfo.uid, pkg.packageName,
8983                                ArtManager.getProfileName(null))) {
8984                            Log.e(TAG, "Installer failed to copy system profile!");
8985                        } else {
8986                            // Disabled as this causes speed-profile compilation during first boot
8987                            // even if things are already compiled.
8988                            // useProfileForDexopt = true;
8989                        }
8990                    } catch (Exception e) {
8991                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
8992                                e);
8993                    }
8994                } else {
8995                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8996                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
8997                    // minimize the number off apps being speed-profile compiled during first boot.
8998                    // The other paths will not change the filter.
8999                    if (disabledPs != null && disabledPs.pkg.isStub) {
9000                        // The package is the stub one, remove the stub suffix to get the normal
9001                        // package and APK names.
9002                        String systemProfilePath =
9003                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
9004                        profileFile = new File(systemProfilePath);
9005                        // If we have a profile for a compressed APK, copy it to the reference
9006                        // location.
9007                        // Note that copying the profile here will cause it to override the
9008                        // reference profile every OTA even though the existing reference profile
9009                        // may have more data. We can't copy during decompression since the
9010                        // directories are not set up at that point.
9011                        if (profileFile.exists()) {
9012                            try {
9013                                // We could also do this lazily before calling dexopt in
9014                                // PackageDexOptimizer to prevent this happening on first boot. The
9015                                // issue is that we don't have a good way to say "do this only
9016                                // once".
9017                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9018                                        pkg.applicationInfo.uid, pkg.packageName,
9019                                        ArtManager.getProfileName(null))) {
9020                                    Log.e(TAG, "Failed to copy system profile for stub package!");
9021                                } else {
9022                                    useProfileForDexopt = true;
9023                                }
9024                            } catch (Exception e) {
9025                                Log.e(TAG, "Failed to copy profile " +
9026                                        profileFile.getAbsolutePath() + " ", e);
9027                            }
9028                        }
9029                    }
9030                }
9031            }
9032
9033            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9034                if (DEBUG_DEXOPT) {
9035                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9036                }
9037                numberOfPackagesSkipped++;
9038                continue;
9039            }
9040
9041            if (DEBUG_DEXOPT) {
9042                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9043                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9044            }
9045
9046            if (showDialog) {
9047                try {
9048                    ActivityManager.getService().showBootMessage(
9049                            mContext.getResources().getString(R.string.android_upgrading_apk,
9050                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9051                } catch (RemoteException e) {
9052                }
9053                synchronized (mPackages) {
9054                    mDexOptDialogShown = true;
9055                }
9056            }
9057
9058            String pkgCompilerFilter = compilerFilter;
9059            if (useProfileForDexopt) {
9060                // Use background dexopt mode to try and use the profile. Note that this does not
9061                // guarantee usage of the profile.
9062                pkgCompilerFilter =
9063                        PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
9064                                PackageManagerService.REASON_BACKGROUND_DEXOPT);
9065            }
9066
9067            // checkProfiles is false to avoid merging profiles during boot which
9068            // might interfere with background compilation (b/28612421).
9069            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9070            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9071            // trade-off worth doing to save boot time work.
9072            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9073            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9074                    pkg.packageName,
9075                    pkgCompilerFilter,
9076                    dexoptFlags));
9077
9078            switch (primaryDexOptStaus) {
9079                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9080                    numberOfPackagesOptimized++;
9081                    break;
9082                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9083                    numberOfPackagesSkipped++;
9084                    break;
9085                case PackageDexOptimizer.DEX_OPT_FAILED:
9086                    numberOfPackagesFailed++;
9087                    break;
9088                default:
9089                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9090                    break;
9091            }
9092        }
9093
9094        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9095                numberOfPackagesFailed };
9096    }
9097
9098    @Override
9099    public void notifyPackageUse(String packageName, int reason) {
9100        synchronized (mPackages) {
9101            final int callingUid = Binder.getCallingUid();
9102            final int callingUserId = UserHandle.getUserId(callingUid);
9103            if (getInstantAppPackageName(callingUid) != null) {
9104                if (!isCallerSameApp(packageName, callingUid)) {
9105                    return;
9106                }
9107            } else {
9108                if (isInstantApp(packageName, callingUserId)) {
9109                    return;
9110                }
9111            }
9112            notifyPackageUseLocked(packageName, reason);
9113        }
9114    }
9115
9116    private void notifyPackageUseLocked(String packageName, int reason) {
9117        final PackageParser.Package p = mPackages.get(packageName);
9118        if (p == null) {
9119            return;
9120        }
9121        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9122    }
9123
9124    @Override
9125    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9126            List<String> classPaths, String loaderIsa) {
9127        int userId = UserHandle.getCallingUserId();
9128        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9129        if (ai == null) {
9130            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9131                + loadingPackageName + ", user=" + userId);
9132            return;
9133        }
9134        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9135    }
9136
9137    @Override
9138    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9139            IDexModuleRegisterCallback callback) {
9140        int userId = UserHandle.getCallingUserId();
9141        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9142        DexManager.RegisterDexModuleResult result;
9143        if (ai == null) {
9144            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9145                     " calling user. package=" + packageName + ", user=" + userId);
9146            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9147        } else {
9148            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9149        }
9150
9151        if (callback != null) {
9152            mHandler.post(() -> {
9153                try {
9154                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9155                } catch (RemoteException e) {
9156                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9157                }
9158            });
9159        }
9160    }
9161
9162    /**
9163     * Ask the package manager to perform a dex-opt with the given compiler filter.
9164     *
9165     * Note: exposed only for the shell command to allow moving packages explicitly to a
9166     *       definite state.
9167     */
9168    @Override
9169    public boolean performDexOptMode(String packageName,
9170            boolean checkProfiles, String targetCompilerFilter, boolean force,
9171            boolean bootComplete, String splitName) {
9172        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9173                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9174                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9175        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9176                splitName, flags));
9177    }
9178
9179    /**
9180     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9181     * secondary dex files belonging to the given package.
9182     *
9183     * Note: exposed only for the shell command to allow moving packages explicitly to a
9184     *       definite state.
9185     */
9186    @Override
9187    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9188            boolean force) {
9189        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9190                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9191                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9192                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9193        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9194    }
9195
9196    /*package*/ boolean performDexOpt(DexoptOptions options) {
9197        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9198            return false;
9199        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9200            return false;
9201        }
9202
9203        if (options.isDexoptOnlySecondaryDex()) {
9204            return mDexManager.dexoptSecondaryDex(options);
9205        } else {
9206            int dexoptStatus = performDexOptWithStatus(options);
9207            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9208        }
9209    }
9210
9211    /**
9212     * Perform dexopt on the given package and return one of following result:
9213     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9214     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9215     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9216     */
9217    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9218        return performDexOptTraced(options);
9219    }
9220
9221    private int performDexOptTraced(DexoptOptions options) {
9222        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9223        try {
9224            return performDexOptInternal(options);
9225        } finally {
9226            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9227        }
9228    }
9229
9230    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9231    // if the package can now be considered up to date for the given filter.
9232    private int performDexOptInternal(DexoptOptions options) {
9233        PackageParser.Package p;
9234        synchronized (mPackages) {
9235            p = mPackages.get(options.getPackageName());
9236            if (p == null) {
9237                // Package could not be found. Report failure.
9238                return PackageDexOptimizer.DEX_OPT_FAILED;
9239            }
9240            mPackageUsage.maybeWriteAsync(mPackages);
9241            mCompilerStats.maybeWriteAsync();
9242        }
9243        long callingId = Binder.clearCallingIdentity();
9244        try {
9245            synchronized (mInstallLock) {
9246                return performDexOptInternalWithDependenciesLI(p, options);
9247            }
9248        } finally {
9249            Binder.restoreCallingIdentity(callingId);
9250        }
9251    }
9252
9253    public ArraySet<String> getOptimizablePackages() {
9254        ArraySet<String> pkgs = new ArraySet<String>();
9255        synchronized (mPackages) {
9256            for (PackageParser.Package p : mPackages.values()) {
9257                if (PackageDexOptimizer.canOptimizePackage(p)) {
9258                    pkgs.add(p.packageName);
9259                }
9260            }
9261        }
9262        return pkgs;
9263    }
9264
9265    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9266            DexoptOptions options) {
9267        // Select the dex optimizer based on the force parameter.
9268        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9269        //       allocate an object here.
9270        PackageDexOptimizer pdo = options.isForce()
9271                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9272                : mPackageDexOptimizer;
9273
9274        // Dexopt all dependencies first. Note: we ignore the return value and march on
9275        // on errors.
9276        // Note that we are going to call performDexOpt on those libraries as many times as
9277        // they are referenced in packages. When we do a batch of performDexOpt (for example
9278        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9279        // and the first package that uses the library will dexopt it. The
9280        // others will see that the compiled code for the library is up to date.
9281        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9282        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9283        if (!deps.isEmpty()) {
9284            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9285                    options.getCompilerFilter(), options.getSplitName(),
9286                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9287            for (PackageParser.Package depPackage : deps) {
9288                // TODO: Analyze and investigate if we (should) profile libraries.
9289                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9290                        getOrCreateCompilerPackageStats(depPackage),
9291                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9292            }
9293        }
9294        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9295                getOrCreateCompilerPackageStats(p),
9296                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9297    }
9298
9299    /**
9300     * Reconcile the information we have about the secondary dex files belonging to
9301     * {@code packagName} and the actual dex files. For all dex files that were
9302     * deleted, update the internal records and delete the generated oat files.
9303     */
9304    @Override
9305    public void reconcileSecondaryDexFiles(String packageName) {
9306        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9307            return;
9308        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9309            return;
9310        }
9311        mDexManager.reconcileSecondaryDexFiles(packageName);
9312    }
9313
9314    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9315    // a reference there.
9316    /*package*/ DexManager getDexManager() {
9317        return mDexManager;
9318    }
9319
9320    /**
9321     * Execute the background dexopt job immediately.
9322     */
9323    @Override
9324    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9325        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9326            return false;
9327        }
9328        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9329    }
9330
9331    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9332        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9333                || p.usesStaticLibraries != null) {
9334            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9335            Set<String> collectedNames = new HashSet<>();
9336            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9337
9338            retValue.remove(p);
9339
9340            return retValue;
9341        } else {
9342            return Collections.emptyList();
9343        }
9344    }
9345
9346    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9347            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9348        if (!collectedNames.contains(p.packageName)) {
9349            collectedNames.add(p.packageName);
9350            collected.add(p);
9351
9352            if (p.usesLibraries != null) {
9353                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9354                        null, collected, collectedNames);
9355            }
9356            if (p.usesOptionalLibraries != null) {
9357                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9358                        null, collected, collectedNames);
9359            }
9360            if (p.usesStaticLibraries != null) {
9361                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9362                        p.usesStaticLibrariesVersions, collected, collectedNames);
9363            }
9364        }
9365    }
9366
9367    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9368            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9369        final int libNameCount = libs.size();
9370        for (int i = 0; i < libNameCount; i++) {
9371            String libName = libs.get(i);
9372            long version = (versions != null && versions.length == libNameCount)
9373                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9374            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9375            if (libPkg != null) {
9376                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9377            }
9378        }
9379    }
9380
9381    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9382        synchronized (mPackages) {
9383            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9384            if (libEntry != null) {
9385                return mPackages.get(libEntry.apk);
9386            }
9387            return null;
9388        }
9389    }
9390
9391    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9392        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9393        if (versionedLib == null) {
9394            return null;
9395        }
9396        return versionedLib.get(version);
9397    }
9398
9399    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9400        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9401                pkg.staticSharedLibName);
9402        if (versionedLib == null) {
9403            return null;
9404        }
9405        long previousLibVersion = -1;
9406        final int versionCount = versionedLib.size();
9407        for (int i = 0; i < versionCount; i++) {
9408            final long libVersion = versionedLib.keyAt(i);
9409            if (libVersion < pkg.staticSharedLibVersion) {
9410                previousLibVersion = Math.max(previousLibVersion, libVersion);
9411            }
9412        }
9413        if (previousLibVersion >= 0) {
9414            return versionedLib.get(previousLibVersion);
9415        }
9416        return null;
9417    }
9418
9419    public void shutdown() {
9420        mPackageUsage.writeNow(mPackages);
9421        mCompilerStats.writeNow();
9422        mDexManager.writePackageDexUsageNow();
9423    }
9424
9425    @Override
9426    public void dumpProfiles(String packageName) {
9427        PackageParser.Package pkg;
9428        synchronized (mPackages) {
9429            pkg = mPackages.get(packageName);
9430            if (pkg == null) {
9431                throw new IllegalArgumentException("Unknown package: " + packageName);
9432            }
9433        }
9434        /* Only the shell, root, or the app user should be able to dump profiles. */
9435        int callingUid = Binder.getCallingUid();
9436        if (callingUid != Process.SHELL_UID &&
9437            callingUid != Process.ROOT_UID &&
9438            callingUid != pkg.applicationInfo.uid) {
9439            throw new SecurityException("dumpProfiles");
9440        }
9441
9442        synchronized (mInstallLock) {
9443            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9444            mArtManagerService.dumpProfiles(pkg);
9445            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9446        }
9447    }
9448
9449    @Override
9450    public void forceDexOpt(String packageName) {
9451        enforceSystemOrRoot("forceDexOpt");
9452
9453        PackageParser.Package pkg;
9454        synchronized (mPackages) {
9455            pkg = mPackages.get(packageName);
9456            if (pkg == null) {
9457                throw new IllegalArgumentException("Unknown package: " + packageName);
9458            }
9459        }
9460
9461        synchronized (mInstallLock) {
9462            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9463
9464            // Whoever is calling forceDexOpt wants a compiled package.
9465            // Don't use profiles since that may cause compilation to be skipped.
9466            final int res = performDexOptInternalWithDependenciesLI(
9467                    pkg,
9468                    new DexoptOptions(packageName,
9469                            getDefaultCompilerFilter(),
9470                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9471
9472            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9473            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9474                throw new IllegalStateException("Failed to dexopt: " + res);
9475            }
9476        }
9477    }
9478
9479    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9480        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9481            Slog.w(TAG, "Unable to update from " + oldPkg.name
9482                    + " to " + newPkg.packageName
9483                    + ": old package not in system partition");
9484            return false;
9485        } else if (mPackages.get(oldPkg.name) != null) {
9486            Slog.w(TAG, "Unable to update from " + oldPkg.name
9487                    + " to " + newPkg.packageName
9488                    + ": old package still exists");
9489            return false;
9490        }
9491        return true;
9492    }
9493
9494    void removeCodePathLI(File codePath) {
9495        if (codePath.isDirectory()) {
9496            try {
9497                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9498            } catch (InstallerException e) {
9499                Slog.w(TAG, "Failed to remove code path", e);
9500            }
9501        } else {
9502            codePath.delete();
9503        }
9504    }
9505
9506    private int[] resolveUserIds(int userId) {
9507        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9508    }
9509
9510    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9511        if (pkg == null) {
9512            Slog.wtf(TAG, "Package was null!", new Throwable());
9513            return;
9514        }
9515        clearAppDataLeafLIF(pkg, userId, flags);
9516        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9517        for (int i = 0; i < childCount; i++) {
9518            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9519        }
9520
9521        clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
9522    }
9523
9524    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9525        final PackageSetting ps;
9526        synchronized (mPackages) {
9527            ps = mSettings.mPackages.get(pkg.packageName);
9528        }
9529        for (int realUserId : resolveUserIds(userId)) {
9530            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9531            try {
9532                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9533                        ceDataInode);
9534            } catch (InstallerException e) {
9535                Slog.w(TAG, String.valueOf(e));
9536            }
9537        }
9538    }
9539
9540    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9541        if (pkg == null) {
9542            Slog.wtf(TAG, "Package was null!", new Throwable());
9543            return;
9544        }
9545        destroyAppDataLeafLIF(pkg, userId, flags);
9546        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9547        for (int i = 0; i < childCount; i++) {
9548            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9549        }
9550    }
9551
9552    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9553        final PackageSetting ps;
9554        synchronized (mPackages) {
9555            ps = mSettings.mPackages.get(pkg.packageName);
9556        }
9557        for (int realUserId : resolveUserIds(userId)) {
9558            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9559            try {
9560                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9561                        ceDataInode);
9562            } catch (InstallerException e) {
9563                Slog.w(TAG, String.valueOf(e));
9564            }
9565            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9566        }
9567    }
9568
9569    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9570        if (pkg == null) {
9571            Slog.wtf(TAG, "Package was null!", new Throwable());
9572            return;
9573        }
9574        destroyAppProfilesLeafLIF(pkg);
9575        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9576        for (int i = 0; i < childCount; i++) {
9577            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9578        }
9579    }
9580
9581    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9582        try {
9583            mInstaller.destroyAppProfiles(pkg.packageName);
9584        } catch (InstallerException e) {
9585            Slog.w(TAG, String.valueOf(e));
9586        }
9587    }
9588
9589    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9590        if (pkg == null) {
9591            Slog.wtf(TAG, "Package was null!", new Throwable());
9592            return;
9593        }
9594        mArtManagerService.clearAppProfiles(pkg);
9595        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9596        for (int i = 0; i < childCount; i++) {
9597            mArtManagerService.clearAppProfiles(pkg.childPackages.get(i));
9598        }
9599    }
9600
9601    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9602            long lastUpdateTime) {
9603        // Set parent install/update time
9604        PackageSetting ps = (PackageSetting) pkg.mExtras;
9605        if (ps != null) {
9606            ps.firstInstallTime = firstInstallTime;
9607            ps.lastUpdateTime = lastUpdateTime;
9608        }
9609        // Set children install/update time
9610        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9611        for (int i = 0; i < childCount; i++) {
9612            PackageParser.Package childPkg = pkg.childPackages.get(i);
9613            ps = (PackageSetting) childPkg.mExtras;
9614            if (ps != null) {
9615                ps.firstInstallTime = firstInstallTime;
9616                ps.lastUpdateTime = lastUpdateTime;
9617            }
9618        }
9619    }
9620
9621    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9622            SharedLibraryEntry file,
9623            PackageParser.Package changingLib) {
9624        if (file.path != null) {
9625            usesLibraryFiles.add(file.path);
9626            return;
9627        }
9628        PackageParser.Package p = mPackages.get(file.apk);
9629        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9630            // If we are doing this while in the middle of updating a library apk,
9631            // then we need to make sure to use that new apk for determining the
9632            // dependencies here.  (We haven't yet finished committing the new apk
9633            // to the package manager state.)
9634            if (p == null || p.packageName.equals(changingLib.packageName)) {
9635                p = changingLib;
9636            }
9637        }
9638        if (p != null) {
9639            usesLibraryFiles.addAll(p.getAllCodePaths());
9640            if (p.usesLibraryFiles != null) {
9641                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9642            }
9643        }
9644    }
9645
9646    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9647            PackageParser.Package changingLib) throws PackageManagerException {
9648        if (pkg == null) {
9649            return;
9650        }
9651        // The collection used here must maintain the order of addition (so
9652        // that libraries are searched in the correct order) and must have no
9653        // duplicates.
9654        Set<String> usesLibraryFiles = null;
9655        if (pkg.usesLibraries != null) {
9656            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9657                    null, null, pkg.packageName, changingLib, true,
9658                    pkg.applicationInfo.targetSdkVersion, null);
9659        }
9660        if (pkg.usesStaticLibraries != null) {
9661            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9662                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9663                    pkg.packageName, changingLib, true,
9664                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9665        }
9666        if (pkg.usesOptionalLibraries != null) {
9667            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9668                    null, null, pkg.packageName, changingLib, false,
9669                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9670        }
9671        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9672            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9673        } else {
9674            pkg.usesLibraryFiles = null;
9675        }
9676    }
9677
9678    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9679            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9680            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9681            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9682            throws PackageManagerException {
9683        final int libCount = requestedLibraries.size();
9684        for (int i = 0; i < libCount; i++) {
9685            final String libName = requestedLibraries.get(i);
9686            final long libVersion = requiredVersions != null ? requiredVersions[i]
9687                    : SharedLibraryInfo.VERSION_UNDEFINED;
9688            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9689            if (libEntry == null) {
9690                if (required) {
9691                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9692                            "Package " + packageName + " requires unavailable shared library "
9693                                    + libName + "; failing!");
9694                } else if (DEBUG_SHARED_LIBRARIES) {
9695                    Slog.i(TAG, "Package " + packageName
9696                            + " desires unavailable shared library "
9697                            + libName + "; ignoring!");
9698                }
9699            } else {
9700                if (requiredVersions != null && requiredCertDigests != null) {
9701                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9702                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9703                            "Package " + packageName + " requires unavailable static shared"
9704                                    + " library " + libName + " version "
9705                                    + libEntry.info.getLongVersion() + "; failing!");
9706                    }
9707
9708                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9709                    if (libPkg == null) {
9710                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9711                                "Package " + packageName + " requires unavailable static shared"
9712                                        + " library; failing!");
9713                    }
9714
9715                    final String[] expectedCertDigests = requiredCertDigests[i];
9716                    // For apps targeting O MR1 we require explicit enumeration of all certs.
9717                    final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9718                            ? PackageUtils.computeSignaturesSha256Digests(
9719                            libPkg.mSigningDetails.signatures)
9720                            : PackageUtils.computeSignaturesSha256Digests(
9721                                    new Signature[]{libPkg.mSigningDetails.signatures[0]});
9722
9723                    // Take a shortcut if sizes don't match. Note that if an app doesn't
9724                    // target O we don't parse the "additional-certificate" tags similarly
9725                    // how we only consider all certs only for apps targeting O (see above).
9726                    // Therefore, the size check is safe to make.
9727                    if (expectedCertDigests.length != libCertDigests.length) {
9728                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9729                                "Package " + packageName + " requires differently signed" +
9730                                        " static shared library; failing!");
9731                    }
9732
9733                    // Use a predictable order as signature order may vary
9734                    Arrays.sort(libCertDigests);
9735                    Arrays.sort(expectedCertDigests);
9736
9737                    final int certCount = libCertDigests.length;
9738                    for (int j = 0; j < certCount; j++) {
9739                        if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9740                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9741                                    "Package " + packageName + " requires differently signed" +
9742                                            " static shared library; failing!");
9743                        }
9744                    }
9745                }
9746
9747                if (outUsedLibraries == null) {
9748                    // Use LinkedHashSet to preserve the order of files added to
9749                    // usesLibraryFiles while eliminating duplicates.
9750                    outUsedLibraries = new LinkedHashSet<>();
9751                }
9752                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9753            }
9754        }
9755        return outUsedLibraries;
9756    }
9757
9758    private static boolean hasString(List<String> list, List<String> which) {
9759        if (list == null) {
9760            return false;
9761        }
9762        for (int i=list.size()-1; i>=0; i--) {
9763            for (int j=which.size()-1; j>=0; j--) {
9764                if (which.get(j).equals(list.get(i))) {
9765                    return true;
9766                }
9767            }
9768        }
9769        return false;
9770    }
9771
9772    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9773            PackageParser.Package changingPkg) {
9774        ArrayList<PackageParser.Package> res = null;
9775        for (PackageParser.Package pkg : mPackages.values()) {
9776            if (changingPkg != null
9777                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9778                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9779                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9780                            changingPkg.staticSharedLibName)) {
9781                return null;
9782            }
9783            if (res == null) {
9784                res = new ArrayList<>();
9785            }
9786            res.add(pkg);
9787            try {
9788                updateSharedLibrariesLPr(pkg, changingPkg);
9789            } catch (PackageManagerException e) {
9790                // If a system app update or an app and a required lib missing we
9791                // delete the package and for updated system apps keep the data as
9792                // it is better for the user to reinstall than to be in an limbo
9793                // state. Also libs disappearing under an app should never happen
9794                // - just in case.
9795                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9796                    final int flags = pkg.isUpdatedSystemApp()
9797                            ? PackageManager.DELETE_KEEP_DATA : 0;
9798                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9799                            flags , null, true, null);
9800                }
9801                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9802            }
9803        }
9804        return res;
9805    }
9806
9807    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9808            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9809            @Nullable UserHandle user) throws PackageManagerException {
9810        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9811        // If the package has children and this is the first dive in the function
9812        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9813        // whether all packages (parent and children) would be successfully scanned
9814        // before the actual scan since scanning mutates internal state and we want
9815        // to atomically install the package and its children.
9816        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9817            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9818                scanFlags |= SCAN_CHECK_ONLY;
9819            }
9820        } else {
9821            scanFlags &= ~SCAN_CHECK_ONLY;
9822        }
9823
9824        final PackageParser.Package scannedPkg;
9825        try {
9826            // Scan the parent
9827            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9828            // Scan the children
9829            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9830            for (int i = 0; i < childCount; i++) {
9831                PackageParser.Package childPkg = pkg.childPackages.get(i);
9832                scanPackageNewLI(childPkg, parseFlags,
9833                        scanFlags, currentTime, user);
9834            }
9835        } finally {
9836            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9837        }
9838
9839        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9840            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9841        }
9842
9843        return scannedPkg;
9844    }
9845
9846    /** The result of a package scan. */
9847    private static class ScanResult {
9848        /** Whether or not the package scan was successful */
9849        public final boolean success;
9850        /**
9851         * The final package settings. This may be the same object passed in
9852         * the {@link ScanRequest}, but, with modified values.
9853         */
9854        @Nullable public final PackageSetting pkgSetting;
9855        /** ABI code paths that have changed in the package scan */
9856        @Nullable public final List<String> changedAbiCodePath;
9857        public ScanResult(
9858                boolean success,
9859                @Nullable PackageSetting pkgSetting,
9860                @Nullable List<String> changedAbiCodePath) {
9861            this.success = success;
9862            this.pkgSetting = pkgSetting;
9863            this.changedAbiCodePath = changedAbiCodePath;
9864        }
9865    }
9866
9867    /** A package to be scanned */
9868    private static class ScanRequest {
9869        /** The parsed package */
9870        @NonNull public final PackageParser.Package pkg;
9871        /** Shared user settings, if the package has a shared user */
9872        @Nullable public final SharedUserSetting sharedUserSetting;
9873        /**
9874         * Package settings of the currently installed version.
9875         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9876         * during scan.
9877         */
9878        @Nullable public final PackageSetting pkgSetting;
9879        /** A copy of the settings for the currently installed version */
9880        @Nullable public final PackageSetting oldPkgSetting;
9881        /** Package settings for the disabled version on the /system partition */
9882        @Nullable public final PackageSetting disabledPkgSetting;
9883        /** Package settings for the installed version under its original package name */
9884        @Nullable public final PackageSetting originalPkgSetting;
9885        /** The real package name of a renamed application */
9886        @Nullable public final String realPkgName;
9887        public final @ParseFlags int parseFlags;
9888        public final @ScanFlags int scanFlags;
9889        /** The user for which the package is being scanned */
9890        @Nullable public final UserHandle user;
9891        /** Whether or not the platform package is being scanned */
9892        public final boolean isPlatformPackage;
9893        public ScanRequest(
9894                @NonNull PackageParser.Package pkg,
9895                @Nullable SharedUserSetting sharedUserSetting,
9896                @Nullable PackageSetting pkgSetting,
9897                @Nullable PackageSetting disabledPkgSetting,
9898                @Nullable PackageSetting originalPkgSetting,
9899                @Nullable String realPkgName,
9900                @ParseFlags int parseFlags,
9901                @ScanFlags int scanFlags,
9902                boolean isPlatformPackage,
9903                @Nullable UserHandle user) {
9904            this.pkg = pkg;
9905            this.pkgSetting = pkgSetting;
9906            this.sharedUserSetting = sharedUserSetting;
9907            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9908            this.disabledPkgSetting = disabledPkgSetting;
9909            this.originalPkgSetting = originalPkgSetting;
9910            this.realPkgName = realPkgName;
9911            this.parseFlags = parseFlags;
9912            this.scanFlags = scanFlags;
9913            this.isPlatformPackage = isPlatformPackage;
9914            this.user = user;
9915        }
9916    }
9917
9918    /**
9919     * Returns the actual scan flags depending upon the state of the other settings.
9920     * <p>Updated system applications will not have the following flags set
9921     * by default and need to be adjusted after the fact:
9922     * <ul>
9923     * <li>{@link #SCAN_AS_SYSTEM}</li>
9924     * <li>{@link #SCAN_AS_PRIVILEGED}</li>
9925     * <li>{@link #SCAN_AS_OEM}</li>
9926     * <li>{@link #SCAN_AS_VENDOR}</li>
9927     * <li>{@link #SCAN_AS_PRODUCT}</li>
9928     * <li>{@link #SCAN_AS_INSTANT_APP}</li>
9929     * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li>
9930     * </ul>
9931     */
9932    private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags,
9933            PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user,
9934            PackageParser.Package pkg) {
9935        if (disabledPkgSetting != null) {
9936            // updated system application, must at least have SCAN_AS_SYSTEM
9937            scanFlags |= SCAN_AS_SYSTEM;
9938            if ((disabledPkgSetting.pkgPrivateFlags
9939                    & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9940                scanFlags |= SCAN_AS_PRIVILEGED;
9941            }
9942            if ((disabledPkgSetting.pkgPrivateFlags
9943                    & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
9944                scanFlags |= SCAN_AS_OEM;
9945            }
9946            if ((disabledPkgSetting.pkgPrivateFlags
9947                    & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
9948                scanFlags |= SCAN_AS_VENDOR;
9949            }
9950            if ((disabledPkgSetting.pkgPrivateFlags
9951                    & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) {
9952                scanFlags |= SCAN_AS_PRODUCT;
9953            }
9954        }
9955        if (pkgSetting != null) {
9956            final int userId = ((user == null) ? 0 : user.getIdentifier());
9957            if (pkgSetting.getInstantApp(userId)) {
9958                scanFlags |= SCAN_AS_INSTANT_APP;
9959            }
9960            if (pkgSetting.getVirtulalPreload(userId)) {
9961                scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9962            }
9963        }
9964
9965        // Scan as privileged apps that share a user with a priv-app.
9966        if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged()
9967                && (pkg.mSharedUserId != null)) {
9968            SharedUserSetting sharedUserSetting = null;
9969            try {
9970                sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
9971            } catch (PackageManagerException ignore) {}
9972            if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
9973                // Exempt SharedUsers signed with the platform key.
9974                // TODO(b/72378145) Fix this exemption. Force signature apps
9975                // to whitelist their privileged permissions just like other
9976                // priv-apps.
9977                synchronized (mPackages) {
9978                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
9979                    if (!pkg.packageName.equals("android")
9980                            && (compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
9981                                pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
9982                        scanFlags |= SCAN_AS_PRIVILEGED;
9983                    }
9984                }
9985            }
9986        }
9987
9988        return scanFlags;
9989    }
9990
9991    @GuardedBy("mInstallLock")
9992    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
9993            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9994            @Nullable UserHandle user) throws PackageManagerException {
9995
9996        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9997        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
9998        if (realPkgName != null) {
9999            ensurePackageRenamed(pkg, renamedPkgName);
10000        }
10001        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
10002        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10003        final PackageSetting disabledPkgSetting =
10004                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10005
10006        if (mTransferedPackages.contains(pkg.packageName)) {
10007            Slog.w(TAG, "Package " + pkg.packageName
10008                    + " was transferred to another, but its .apk remains");
10009        }
10010
10011        scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg);
10012        synchronized (mPackages) {
10013            applyPolicy(pkg, parseFlags, scanFlags);
10014            assertPackageIsValid(pkg, parseFlags, scanFlags);
10015
10016            SharedUserSetting sharedUserSetting = null;
10017            if (pkg.mSharedUserId != null) {
10018                // SIDE EFFECTS; may potentially allocate a new shared user
10019                sharedUserSetting = mSettings.getSharedUserLPw(
10020                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10021                if (DEBUG_PACKAGE_SCANNING) {
10022                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10023                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
10024                                + " (uid=" + sharedUserSetting.userId + "):"
10025                                + " packages=" + sharedUserSetting.packages);
10026                }
10027            }
10028
10029            boolean scanSucceeded = false;
10030            try {
10031                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting,
10032                        disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags,
10033                        (pkg == mPlatformPackage), user);
10034                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
10035                if (result.success) {
10036                    commitScanResultsLocked(request, result);
10037                }
10038                scanSucceeded = true;
10039            } finally {
10040                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10041                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
10042                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10043                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10044                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10045                  }
10046            }
10047        }
10048        return pkg;
10049    }
10050
10051    /**
10052     * Commits the package scan and modifies system state.
10053     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
10054     * of committing the package, leaving the system in an inconsistent state.
10055     * This needs to be fixed so, once we get to this point, no errors are
10056     * possible and the system is not left in an inconsistent state.
10057     */
10058    @GuardedBy("mPackages")
10059    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
10060            throws PackageManagerException {
10061        final PackageParser.Package pkg = request.pkg;
10062        final @ParseFlags int parseFlags = request.parseFlags;
10063        final @ScanFlags int scanFlags = request.scanFlags;
10064        final PackageSetting oldPkgSetting = request.oldPkgSetting;
10065        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10066        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10067        final UserHandle user = request.user;
10068        final String realPkgName = request.realPkgName;
10069        final PackageSetting pkgSetting = result.pkgSetting;
10070        final List<String> changedAbiCodePath = result.changedAbiCodePath;
10071        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
10072
10073        if (newPkgSettingCreated) {
10074            if (originalPkgSetting != null) {
10075                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
10076            }
10077            // THROWS: when we can't allocate a user id. add call to check if there's
10078            // enough space to ensure we won't throw; otherwise, don't modify state
10079            mSettings.addUserToSettingLPw(pkgSetting);
10080
10081            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
10082                mTransferedPackages.add(originalPkgSetting.name);
10083            }
10084        }
10085        // TODO(toddke): Consider a method specifically for modifying the Package object
10086        // post scan; or, moving this stuff out of the Package object since it has nothing
10087        // to do with the package on disk.
10088        // We need to have this here because addUserToSettingLPw() is sometimes responsible
10089        // for creating the application ID. If we did this earlier, we would be saving the
10090        // correct ID.
10091        pkg.applicationInfo.uid = pkgSetting.appId;
10092
10093        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10094
10095        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
10096            mTransferedPackages.add(pkg.packageName);
10097        }
10098
10099        // THROWS: when requested libraries that can't be found. it only changes
10100        // the state of the passed in pkg object, so, move to the top of the method
10101        // and allow it to abort
10102        if ((scanFlags & SCAN_BOOTING) == 0
10103                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10104            // Check all shared libraries and map to their actual file path.
10105            // We only do this here for apps not on a system dir, because those
10106            // are the only ones that can fail an install due to this.  We
10107            // will take care of the system apps by updating all of their
10108            // library paths after the scan is done. Also during the initial
10109            // scan don't update any libs as we do this wholesale after all
10110            // apps are scanned to avoid dependency based scanning.
10111            updateSharedLibrariesLPr(pkg, null);
10112        }
10113
10114        // All versions of a static shared library are referenced with the same
10115        // package name. Internally, we use a synthetic package name to allow
10116        // multiple versions of the same shared library to be installed. So,
10117        // we need to generate the synthetic package name of the latest shared
10118        // library in order to compare signatures.
10119        PackageSetting signatureCheckPs = pkgSetting;
10120        if (pkg.applicationInfo.isStaticSharedLibrary()) {
10121            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10122            if (libraryEntry != null) {
10123                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10124            }
10125        }
10126
10127        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10128        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
10129            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
10130                // We just determined the app is signed correctly, so bring
10131                // over the latest parsed certs.
10132                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10133            } else {
10134                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10135                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10136                            "Package " + pkg.packageName + " upgrade keys do not match the "
10137                                    + "previously installed version");
10138                } else {
10139                    pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10140                    String msg = "System package " + pkg.packageName
10141                            + " signature changed; retaining data.";
10142                    reportSettingsProblem(Log.WARN, msg);
10143                }
10144            }
10145        } else {
10146            try {
10147                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
10148                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
10149                final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting,
10150                        pkg.mSigningDetails, compareCompat, compareRecover);
10151                // The new KeySets will be re-added later in the scanning process.
10152                if (compatMatch) {
10153                    synchronized (mPackages) {
10154                        ksms.removeAppKeySetDataLPw(pkg.packageName);
10155                    }
10156                }
10157                // We just determined the app is signed correctly, so bring
10158                // over the latest parsed certs.
10159                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10160            } catch (PackageManagerException e) {
10161                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10162                    throw e;
10163                }
10164                // The signature has changed, but this package is in the system
10165                // image...  let's recover!
10166                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10167                // However...  if this package is part of a shared user, but it
10168                // doesn't match the signature of the shared user, let's fail.
10169                // What this means is that you can't change the signatures
10170                // associated with an overall shared user, which doesn't seem all
10171                // that unreasonable.
10172                if (signatureCheckPs.sharedUser != null) {
10173                    if (compareSignatures(
10174                            signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures,
10175                            pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) {
10176                        throw new PackageManagerException(
10177                                INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10178                                "Signature mismatch for shared user: "
10179                                        + pkgSetting.sharedUser);
10180                    }
10181                }
10182                // File a report about this.
10183                String msg = "System package " + pkg.packageName
10184                        + " signature changed; retaining data.";
10185                reportSettingsProblem(Log.WARN, msg);
10186            }
10187        }
10188
10189        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10190            // This package wants to adopt ownership of permissions from
10191            // another package.
10192            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10193                final String origName = pkg.mAdoptPermissions.get(i);
10194                final PackageSetting orig = mSettings.getPackageLPr(origName);
10195                if (orig != null) {
10196                    if (verifyPackageUpdateLPr(orig, pkg)) {
10197                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
10198                                + pkg.packageName);
10199                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10200                    }
10201                }
10202            }
10203        }
10204
10205        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
10206            for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) {
10207                final String codePathString = changedAbiCodePath.get(i);
10208                try {
10209                    mInstaller.rmdex(codePathString,
10210                            getDexCodeInstructionSet(getPreferredInstructionSet()));
10211                } catch (InstallerException ignored) {
10212                }
10213            }
10214        }
10215
10216        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10217            if (oldPkgSetting != null) {
10218                synchronized (mPackages) {
10219                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
10220                }
10221            }
10222        } else {
10223            final int userId = user == null ? 0 : user.getIdentifier();
10224            // Modify state for the given package setting
10225            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10226                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10227            if (pkgSetting.getInstantApp(userId)) {
10228                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10229            }
10230        }
10231    }
10232
10233    /**
10234     * Returns the "real" name of the package.
10235     * <p>This may differ from the package's actual name if the application has already
10236     * been installed under one of this package's original names.
10237     */
10238    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
10239            @Nullable String renamedPkgName) {
10240        if (isPackageRenamed(pkg, renamedPkgName)) {
10241            return pkg.mRealPackage;
10242        }
10243        return null;
10244    }
10245
10246    /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
10247    private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
10248            @Nullable String renamedPkgName) {
10249        return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
10250    }
10251
10252    /**
10253     * Returns the original package setting.
10254     * <p>A package can migrate its name during an update. In this scenario, a package
10255     * designates a set of names that it considers as one of its original names.
10256     * <p>An original package must be signed identically and it must have the same
10257     * shared user [if any].
10258     */
10259    @GuardedBy("mPackages")
10260    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
10261            @Nullable String renamedPkgName) {
10262        if (!isPackageRenamed(pkg, renamedPkgName)) {
10263            return null;
10264        }
10265        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
10266            final PackageSetting originalPs =
10267                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
10268            if (originalPs != null) {
10269                // the package is already installed under its original name...
10270                // but, should we use it?
10271                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
10272                    // the new package is incompatible with the original
10273                    continue;
10274                } else if (originalPs.sharedUser != null) {
10275                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
10276                        // the shared user id is incompatible with the original
10277                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
10278                                + " to " + pkg.packageName + ": old uid "
10279                                + originalPs.sharedUser.name
10280                                + " differs from " + pkg.mSharedUserId);
10281                        continue;
10282                    }
10283                    // TODO: Add case when shared user id is added [b/28144775]
10284                } else {
10285                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10286                            + pkg.packageName + " to old name " + originalPs.name);
10287                }
10288                return originalPs;
10289            }
10290        }
10291        return null;
10292    }
10293
10294    /**
10295     * Renames the package if it was installed under a different name.
10296     * <p>When we've already installed the package under an original name, update
10297     * the new package so we can continue to have the old name.
10298     */
10299    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10300            @NonNull String renamedPackageName) {
10301        if (pkg.mOriginalPackages == null
10302                || !pkg.mOriginalPackages.contains(renamedPackageName)
10303                || pkg.packageName.equals(renamedPackageName)) {
10304            return;
10305        }
10306        pkg.setPackageName(renamedPackageName);
10307    }
10308
10309    /**
10310     * Just scans the package without any side effects.
10311     * <p>Not entirely true at the moment. There is still one side effect -- this
10312     * method potentially modifies a live {@link PackageSetting} object representing
10313     * the package being scanned. This will be resolved in the future.
10314     *
10315     * @param request Information about the package to be scanned
10316     * @param isUnderFactoryTest Whether or not the device is under factory test
10317     * @param currentTime The current time, in millis
10318     * @return The results of the scan
10319     */
10320    @GuardedBy("mInstallLock")
10321    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10322            boolean isUnderFactoryTest, long currentTime)
10323                    throws PackageManagerException {
10324        final PackageParser.Package pkg = request.pkg;
10325        PackageSetting pkgSetting = request.pkgSetting;
10326        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10327        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10328        final @ParseFlags int parseFlags = request.parseFlags;
10329        final @ScanFlags int scanFlags = request.scanFlags;
10330        final String realPkgName = request.realPkgName;
10331        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10332        final UserHandle user = request.user;
10333        final boolean isPlatformPackage = request.isPlatformPackage;
10334
10335        List<String> changedAbiCodePath = null;
10336
10337        if (DEBUG_PACKAGE_SCANNING) {
10338            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10339                Log.d(TAG, "Scanning package " + pkg.packageName);
10340        }
10341
10342        if (Build.IS_DEBUGGABLE &&
10343                pkg.isPrivileged() &&
10344                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10345            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10346        }
10347
10348        // Initialize package source and resource directories
10349        final File scanFile = new File(pkg.codePath);
10350        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10351        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10352
10353        // We keep references to the derived CPU Abis from settings in oder to reuse
10354        // them in the case where we're not upgrading or booting for the first time.
10355        String primaryCpuAbiFromSettings = null;
10356        String secondaryCpuAbiFromSettings = null;
10357        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10358
10359        if (!needToDeriveAbi) {
10360            if (pkgSetting != null) {
10361                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10362                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10363            } else {
10364                // Re-scanning a system package after uninstalling updates; need to derive ABI
10365                needToDeriveAbi = true;
10366            }
10367        }
10368
10369        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10370            PackageManagerService.reportSettingsProblem(Log.WARN,
10371                    "Package " + pkg.packageName + " shared user changed from "
10372                            + (pkgSetting.sharedUser != null
10373                            ? pkgSetting.sharedUser.name : "<nothing>")
10374                            + " to "
10375                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10376                            + "; replacing with new");
10377            pkgSetting = null;
10378        }
10379
10380        String[] usesStaticLibraries = null;
10381        if (pkg.usesStaticLibraries != null) {
10382            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10383            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10384        }
10385        final boolean createNewPackage = (pkgSetting == null);
10386        if (createNewPackage) {
10387            final String parentPackageName = (pkg.parentPackage != null)
10388                    ? pkg.parentPackage.packageName : null;
10389            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10390            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10391            // REMOVE SharedUserSetting from method; update in a separate call
10392            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10393                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10394                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10395                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10396                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10397                    user, true /*allowInstall*/, instantApp, virtualPreload,
10398                    parentPackageName, pkg.getChildPackageNames(),
10399                    UserManagerService.getInstance(), usesStaticLibraries,
10400                    pkg.usesStaticLibrariesVersions);
10401        } else {
10402            // REMOVE SharedUserSetting from method; update in a separate call.
10403            //
10404            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10405            // secondaryCpuAbi are not known at this point so we always update them
10406            // to null here, only to reset them at a later point.
10407            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10408                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
10409                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10410                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10411                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10412                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10413        }
10414        if (createNewPackage && originalPkgSetting != null) {
10415            // This is the initial transition from the original package, so,
10416            // fix up the new package's name now. We must do this after looking
10417            // up the package under its new name, so getPackageLP takes care of
10418            // fiddling things correctly.
10419            pkg.setPackageName(originalPkgSetting.name);
10420
10421            // File a report about this.
10422            String msg = "New package " + pkgSetting.realName
10423                    + " renamed to replace old package " + pkgSetting.name;
10424            reportSettingsProblem(Log.WARN, msg);
10425        }
10426
10427        if (disabledPkgSetting != null) {
10428            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10429        }
10430
10431        SELinuxMMAC.assignSeInfoValue(pkg);
10432
10433        pkg.mExtras = pkgSetting;
10434        pkg.applicationInfo.processName = fixProcessName(
10435                pkg.applicationInfo.packageName,
10436                pkg.applicationInfo.processName);
10437
10438        if (!isPlatformPackage) {
10439            // Get all of our default paths setup
10440            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10441        }
10442
10443        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10444
10445        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10446            if (needToDeriveAbi) {
10447                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10448                final boolean extractNativeLibs = !pkg.isLibrary();
10449                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10450                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10451
10452                // Some system apps still use directory structure for native libraries
10453                // in which case we might end up not detecting abi solely based on apk
10454                // structure. Try to detect abi based on directory structure.
10455                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10456                        pkg.applicationInfo.primaryCpuAbi == null) {
10457                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10458                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10459                }
10460            } else {
10461                // This is not a first boot or an upgrade, don't bother deriving the
10462                // ABI during the scan. Instead, trust the value that was stored in the
10463                // package setting.
10464                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10465                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10466
10467                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10468
10469                if (DEBUG_ABI_SELECTION) {
10470                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10471                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10472                            pkg.applicationInfo.secondaryCpuAbi);
10473                }
10474            }
10475        } else {
10476            if ((scanFlags & SCAN_MOVE) != 0) {
10477                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10478                // but we already have this packages package info in the PackageSetting. We just
10479                // use that and derive the native library path based on the new codepath.
10480                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10481                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10482            }
10483
10484            // Set native library paths again. For moves, the path will be updated based on the
10485            // ABIs we've determined above. For non-moves, the path will be updated based on the
10486            // ABIs we determined during compilation, but the path will depend on the final
10487            // package path (after the rename away from the stage path).
10488            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10489        }
10490
10491        // This is a special case for the "system" package, where the ABI is
10492        // dictated by the zygote configuration (and init.rc). We should keep track
10493        // of this ABI so that we can deal with "normal" applications that run under
10494        // the same UID correctly.
10495        if (isPlatformPackage) {
10496            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10497                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10498        }
10499
10500        // If there's a mismatch between the abi-override in the package setting
10501        // and the abiOverride specified for the install. Warn about this because we
10502        // would've already compiled the app without taking the package setting into
10503        // account.
10504        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10505            if (cpuAbiOverride == null && pkg.packageName != null) {
10506                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10507                        " for package " + pkg.packageName);
10508            }
10509        }
10510
10511        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10512        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10513        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10514
10515        // Copy the derived override back to the parsed package, so that we can
10516        // update the package settings accordingly.
10517        pkg.cpuAbiOverride = cpuAbiOverride;
10518
10519        if (DEBUG_ABI_SELECTION) {
10520            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
10521                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10522                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10523        }
10524
10525        // Push the derived path down into PackageSettings so we know what to
10526        // clean up at uninstall time.
10527        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10528
10529        if (DEBUG_ABI_SELECTION) {
10530            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10531                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10532                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10533        }
10534
10535        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10536            // We don't do this here during boot because we can do it all
10537            // at once after scanning all existing packages.
10538            //
10539            // We also do this *before* we perform dexopt on this package, so that
10540            // we can avoid redundant dexopts, and also to make sure we've got the
10541            // code and package path correct.
10542            changedAbiCodePath =
10543                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10544        }
10545
10546        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10547                android.Manifest.permission.FACTORY_TEST)) {
10548            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10549        }
10550
10551        if (isSystemApp(pkg)) {
10552            pkgSetting.isOrphaned = true;
10553        }
10554
10555        // Take care of first install / last update times.
10556        final long scanFileTime = getLastModifiedTime(pkg);
10557        if (currentTime != 0) {
10558            if (pkgSetting.firstInstallTime == 0) {
10559                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10560            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10561                pkgSetting.lastUpdateTime = currentTime;
10562            }
10563        } else if (pkgSetting.firstInstallTime == 0) {
10564            // We need *something*.  Take time time stamp of the file.
10565            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10566        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10567            if (scanFileTime != pkgSetting.timeStamp) {
10568                // A package on the system image has changed; consider this
10569                // to be an update.
10570                pkgSetting.lastUpdateTime = scanFileTime;
10571            }
10572        }
10573        pkgSetting.setTimeStamp(scanFileTime);
10574
10575        pkgSetting.pkg = pkg;
10576        pkgSetting.pkgFlags = pkg.applicationInfo.flags;
10577        if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
10578            pkgSetting.versionCode = pkg.getLongVersionCode();
10579        }
10580        // Update volume if needed
10581        final String volumeUuid = pkg.applicationInfo.volumeUuid;
10582        if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
10583            Slog.i(PackageManagerService.TAG,
10584                    "Update" + (pkgSetting.isSystem() ? " system" : "")
10585                    + " package " + pkg.packageName
10586                    + " volume from " + pkgSetting.volumeUuid
10587                    + " to " + volumeUuid);
10588            pkgSetting.volumeUuid = volumeUuid;
10589        }
10590
10591        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10592    }
10593
10594    /**
10595     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10596     */
10597    private static boolean apkHasCode(String fileName) {
10598        StrictJarFile jarFile = null;
10599        try {
10600            jarFile = new StrictJarFile(fileName,
10601                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10602            return jarFile.findEntry("classes.dex") != null;
10603        } catch (IOException ignore) {
10604        } finally {
10605            try {
10606                if (jarFile != null) {
10607                    jarFile.close();
10608                }
10609            } catch (IOException ignore) {}
10610        }
10611        return false;
10612    }
10613
10614    /**
10615     * Enforces code policy for the package. This ensures that if an APK has
10616     * declared hasCode="true" in its manifest that the APK actually contains
10617     * code.
10618     *
10619     * @throws PackageManagerException If bytecode could not be found when it should exist
10620     */
10621    private static void assertCodePolicy(PackageParser.Package pkg)
10622            throws PackageManagerException {
10623        final boolean shouldHaveCode =
10624                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10625        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10626            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10627                    "Package " + pkg.baseCodePath + " code is missing");
10628        }
10629
10630        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10631            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10632                final boolean splitShouldHaveCode =
10633                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10634                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10635                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10636                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10637                }
10638            }
10639        }
10640    }
10641
10642    /**
10643     * Applies policy to the parsed package based upon the given policy flags.
10644     * Ensures the package is in a good state.
10645     * <p>
10646     * Implementation detail: This method must NOT have any side effect. It would
10647     * ideally be static, but, it requires locks to read system state.
10648     */
10649    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10650            final @ScanFlags int scanFlags) {
10651        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10652            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10653            if (pkg.applicationInfo.isDirectBootAware()) {
10654                // we're direct boot aware; set for all components
10655                for (PackageParser.Service s : pkg.services) {
10656                    s.info.encryptionAware = s.info.directBootAware = true;
10657                }
10658                for (PackageParser.Provider p : pkg.providers) {
10659                    p.info.encryptionAware = p.info.directBootAware = true;
10660                }
10661                for (PackageParser.Activity a : pkg.activities) {
10662                    a.info.encryptionAware = a.info.directBootAware = true;
10663                }
10664                for (PackageParser.Activity r : pkg.receivers) {
10665                    r.info.encryptionAware = r.info.directBootAware = true;
10666                }
10667            }
10668            if (compressedFileExists(pkg.codePath)) {
10669                pkg.isStub = true;
10670            }
10671        } else {
10672            // non system apps can't be flagged as core
10673            pkg.coreApp = false;
10674            // clear flags not applicable to regular apps
10675            pkg.applicationInfo.flags &=
10676                    ~ApplicationInfo.FLAG_PERSISTENT;
10677            pkg.applicationInfo.privateFlags &=
10678                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10679            pkg.applicationInfo.privateFlags &=
10680                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10681            // clear protected broadcasts
10682            pkg.protectedBroadcasts = null;
10683            // cap permission priorities
10684            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10685                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10686                    pkg.permissionGroups.get(i).info.priority = 0;
10687                }
10688            }
10689        }
10690        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10691            // ignore export request for single user receivers
10692            if (pkg.receivers != null) {
10693                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10694                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10695                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10696                        receiver.info.exported = false;
10697                    }
10698                }
10699            }
10700            // ignore export request for single user services
10701            if (pkg.services != null) {
10702                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10703                    final PackageParser.Service service = pkg.services.get(i);
10704                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10705                        service.info.exported = false;
10706                    }
10707                }
10708            }
10709            // ignore export request for single user providers
10710            if (pkg.providers != null) {
10711                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10712                    final PackageParser.Provider provider = pkg.providers.get(i);
10713                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10714                        provider.info.exported = false;
10715                    }
10716                }
10717            }
10718        }
10719
10720        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10721            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10722        }
10723
10724        if ((scanFlags & SCAN_AS_OEM) != 0) {
10725            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10726        }
10727
10728        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10729            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10730        }
10731
10732        if ((scanFlags & SCAN_AS_PRODUCT) != 0) {
10733            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT;
10734        }
10735
10736        if (!isSystemApp(pkg)) {
10737            // Only system apps can use these features.
10738            pkg.mOriginalPackages = null;
10739            pkg.mRealPackage = null;
10740            pkg.mAdoptPermissions = null;
10741        }
10742    }
10743
10744    private static @NonNull <T> T assertNotNull(@Nullable T object, String message)
10745            throws PackageManagerException {
10746        if (object == null) {
10747            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message);
10748        }
10749        return object;
10750    }
10751
10752    /**
10753     * Asserts the parsed package is valid according to the given policy. If the
10754     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10755     * <p>
10756     * Implementation detail: This method must NOT have any side effects. It would
10757     * ideally be static, but, it requires locks to read system state.
10758     *
10759     * @throws PackageManagerException If the package fails any of the validation checks
10760     */
10761    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10762            final @ScanFlags int scanFlags)
10763                    throws PackageManagerException {
10764        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10765            assertCodePolicy(pkg);
10766        }
10767
10768        if (pkg.applicationInfo.getCodePath() == null ||
10769                pkg.applicationInfo.getResourcePath() == null) {
10770            // Bail out. The resource and code paths haven't been set.
10771            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10772                    "Code and resource paths haven't been set correctly");
10773        }
10774
10775        // Make sure we're not adding any bogus keyset info
10776        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10777        ksms.assertScannedPackageValid(pkg);
10778
10779        synchronized (mPackages) {
10780            // The special "android" package can only be defined once
10781            if (pkg.packageName.equals("android")) {
10782                if (mAndroidApplication != null) {
10783                    Slog.w(TAG, "*************************************************");
10784                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10785                    Slog.w(TAG, " codePath=" + pkg.codePath);
10786                    Slog.w(TAG, "*************************************************");
10787                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10788                            "Core android package being redefined.  Skipping.");
10789                }
10790            }
10791
10792            // A package name must be unique; don't allow duplicates
10793            if (mPackages.containsKey(pkg.packageName)) {
10794                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10795                        "Application package " + pkg.packageName
10796                        + " already installed.  Skipping duplicate.");
10797            }
10798
10799            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10800                // Static libs have a synthetic package name containing the version
10801                // but we still want the base name to be unique.
10802                if (mPackages.containsKey(pkg.manifestPackageName)) {
10803                    throw new PackageManagerException(
10804                            "Duplicate static shared lib provider package");
10805                }
10806
10807                // Static shared libraries should have at least O target SDK
10808                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10809                    throw new PackageManagerException(
10810                            "Packages declaring static-shared libs must target O SDK or higher");
10811                }
10812
10813                // Package declaring static a shared lib cannot be instant apps
10814                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10815                    throw new PackageManagerException(
10816                            "Packages declaring static-shared libs cannot be instant apps");
10817                }
10818
10819                // Package declaring static a shared lib cannot be renamed since the package
10820                // name is synthetic and apps can't code around package manager internals.
10821                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10822                    throw new PackageManagerException(
10823                            "Packages declaring static-shared libs cannot be renamed");
10824                }
10825
10826                // Package declaring static a shared lib cannot declare child packages
10827                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10828                    throw new PackageManagerException(
10829                            "Packages declaring static-shared libs cannot have child packages");
10830                }
10831
10832                // Package declaring static a shared lib cannot declare dynamic libs
10833                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10834                    throw new PackageManagerException(
10835                            "Packages declaring static-shared libs cannot declare dynamic libs");
10836                }
10837
10838                // Package declaring static a shared lib cannot declare shared users
10839                if (pkg.mSharedUserId != null) {
10840                    throw new PackageManagerException(
10841                            "Packages declaring static-shared libs cannot declare shared users");
10842                }
10843
10844                // Static shared libs cannot declare activities
10845                if (!pkg.activities.isEmpty()) {
10846                    throw new PackageManagerException(
10847                            "Static shared libs cannot declare activities");
10848                }
10849
10850                // Static shared libs cannot declare services
10851                if (!pkg.services.isEmpty()) {
10852                    throw new PackageManagerException(
10853                            "Static shared libs cannot declare services");
10854                }
10855
10856                // Static shared libs cannot declare providers
10857                if (!pkg.providers.isEmpty()) {
10858                    throw new PackageManagerException(
10859                            "Static shared libs cannot declare content providers");
10860                }
10861
10862                // Static shared libs cannot declare receivers
10863                if (!pkg.receivers.isEmpty()) {
10864                    throw new PackageManagerException(
10865                            "Static shared libs cannot declare broadcast receivers");
10866                }
10867
10868                // Static shared libs cannot declare permission groups
10869                if (!pkg.permissionGroups.isEmpty()) {
10870                    throw new PackageManagerException(
10871                            "Static shared libs cannot declare permission groups");
10872                }
10873
10874                // Static shared libs cannot declare permissions
10875                if (!pkg.permissions.isEmpty()) {
10876                    throw new PackageManagerException(
10877                            "Static shared libs cannot declare permissions");
10878                }
10879
10880                // Static shared libs cannot declare protected broadcasts
10881                if (pkg.protectedBroadcasts != null) {
10882                    throw new PackageManagerException(
10883                            "Static shared libs cannot declare protected broadcasts");
10884                }
10885
10886                // Static shared libs cannot be overlay targets
10887                if (pkg.mOverlayTarget != null) {
10888                    throw new PackageManagerException(
10889                            "Static shared libs cannot be overlay targets");
10890                }
10891
10892                // The version codes must be ordered as lib versions
10893                long minVersionCode = Long.MIN_VALUE;
10894                long maxVersionCode = Long.MAX_VALUE;
10895
10896                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10897                        pkg.staticSharedLibName);
10898                if (versionedLib != null) {
10899                    final int versionCount = versionedLib.size();
10900                    for (int i = 0; i < versionCount; i++) {
10901                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10902                        final long libVersionCode = libInfo.getDeclaringPackage()
10903                                .getLongVersionCode();
10904                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
10905                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10906                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
10907                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10908                        } else {
10909                            minVersionCode = maxVersionCode = libVersionCode;
10910                            break;
10911                        }
10912                    }
10913                }
10914                if (pkg.getLongVersionCode() < minVersionCode
10915                        || pkg.getLongVersionCode() > maxVersionCode) {
10916                    throw new PackageManagerException("Static shared"
10917                            + " lib version codes must be ordered as lib versions");
10918                }
10919            }
10920
10921            // Only privileged apps and updated privileged apps can add child packages.
10922            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10923                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10924                    throw new PackageManagerException("Only privileged apps can add child "
10925                            + "packages. Ignoring package " + pkg.packageName);
10926                }
10927                final int childCount = pkg.childPackages.size();
10928                for (int i = 0; i < childCount; i++) {
10929                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10930                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10931                            childPkg.packageName)) {
10932                        throw new PackageManagerException("Can't override child of "
10933                                + "another disabled app. Ignoring package " + pkg.packageName);
10934                    }
10935                }
10936            }
10937
10938            // If we're only installing presumed-existing packages, require that the
10939            // scanned APK is both already known and at the path previously established
10940            // for it.  Previously unknown packages we pick up normally, but if we have an
10941            // a priori expectation about this package's install presence, enforce it.
10942            // With a singular exception for new system packages. When an OTA contains
10943            // a new system package, we allow the codepath to change from a system location
10944            // to the user-installed location. If we don't allow this change, any newer,
10945            // user-installed version of the application will be ignored.
10946            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10947                if (mExpectingBetter.containsKey(pkg.packageName)) {
10948                    logCriticalInfo(Log.WARN,
10949                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10950                } else {
10951                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10952                    if (known != null) {
10953                        if (DEBUG_PACKAGE_SCANNING) {
10954                            Log.d(TAG, "Examining " + pkg.codePath
10955                                    + " and requiring known paths " + known.codePathString
10956                                    + " & " + known.resourcePathString);
10957                        }
10958                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10959                                || !pkg.applicationInfo.getResourcePath().equals(
10960                                        known.resourcePathString)) {
10961                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10962                                    "Application package " + pkg.packageName
10963                                    + " found at " + pkg.applicationInfo.getCodePath()
10964                                    + " but expected at " + known.codePathString
10965                                    + "; ignoring.");
10966                        }
10967                    } else {
10968                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10969                                "Application package " + pkg.packageName
10970                                + " not found; ignoring.");
10971                    }
10972                }
10973            }
10974
10975            // Verify that this new package doesn't have any content providers
10976            // that conflict with existing packages.  Only do this if the
10977            // package isn't already installed, since we don't want to break
10978            // things that are installed.
10979            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10980                final int N = pkg.providers.size();
10981                int i;
10982                for (i=0; i<N; i++) {
10983                    PackageParser.Provider p = pkg.providers.get(i);
10984                    if (p.info.authority != null) {
10985                        String names[] = p.info.authority.split(";");
10986                        for (int j = 0; j < names.length; j++) {
10987                            if (mProvidersByAuthority.containsKey(names[j])) {
10988                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10989                                final String otherPackageName =
10990                                        ((other != null && other.getComponentName() != null) ?
10991                                                other.getComponentName().getPackageName() : "?");
10992                                throw new PackageManagerException(
10993                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10994                                        "Can't install because provider name " + names[j]
10995                                                + " (in package " + pkg.applicationInfo.packageName
10996                                                + ") is already used by " + otherPackageName);
10997                            }
10998                        }
10999                    }
11000                }
11001            }
11002
11003            // Verify that packages sharing a user with a privileged app are marked as privileged.
11004            if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
11005                SharedUserSetting sharedUserSetting = null;
11006                try {
11007                    sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
11008                } catch (PackageManagerException ignore) {}
11009                if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
11010                    // Exempt SharedUsers signed with the platform key.
11011                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
11012                    if ((platformPkgSetting.signatures.mSigningDetails
11013                            != PackageParser.SigningDetails.UNKNOWN)
11014                            && (compareSignatures(
11015                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11016                                    pkg.mSigningDetails.signatures)
11017                                            != PackageManager.SIGNATURE_MATCH)) {
11018                        throw new PackageManagerException("Apps that share a user with a " +
11019                                "privileged app must themselves be marked as privileged. " +
11020                                pkg.packageName + " shares privileged user " +
11021                                pkg.mSharedUserId + ".");
11022                    }
11023                }
11024            }
11025
11026            // Apply policies specific for runtime resource overlays (RROs).
11027            if (pkg.mOverlayTarget != null) {
11028                // System overlays have some restrictions on their use of the 'static' state.
11029                if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
11030                    // We are scanning a system overlay. This can be the first scan of the
11031                    // system/vendor/oem partition, or an update to the system overlay.
11032                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
11033                        // This must be an update to a system overlay.
11034                        final PackageSetting previousPkg = assertNotNull(
11035                                mSettings.getPackageLPr(pkg.packageName),
11036                                "previous package state not present");
11037
11038                        // Static overlays cannot be updated.
11039                        if (previousPkg.pkg.mOverlayIsStatic) {
11040                            throw new PackageManagerException("Overlay " + pkg.packageName +
11041                                    " is static and cannot be upgraded.");
11042                        // Non-static overlays cannot be converted to static overlays.
11043                        } else if (pkg.mOverlayIsStatic) {
11044                            throw new PackageManagerException("Overlay " + pkg.packageName +
11045                                    " cannot be upgraded into a static overlay.");
11046                        }
11047                    }
11048                } else {
11049                    // The overlay is a non-system overlay. Non-system overlays cannot be static.
11050                    if (pkg.mOverlayIsStatic) {
11051                        throw new PackageManagerException("Overlay " + pkg.packageName +
11052                                " is static but not pre-installed.");
11053                    }
11054
11055                    // The only case where we allow installation of a non-system overlay is when
11056                    // its signature is signed with the platform certificate.
11057                    PackageSetting platformPkgSetting = mSettings.getPackageLPr("android");
11058                    if ((platformPkgSetting.signatures.mSigningDetails
11059                            != PackageParser.SigningDetails.UNKNOWN)
11060                            && (compareSignatures(
11061                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11062                                    pkg.mSigningDetails.signatures)
11063                                            != PackageManager.SIGNATURE_MATCH)) {
11064                        throw new PackageManagerException("Overlay " + pkg.packageName +
11065                                " must be signed with the platform certificate.");
11066                    }
11067                }
11068            }
11069        }
11070    }
11071
11072    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
11073            int type, String declaringPackageName, long declaringVersionCode) {
11074        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11075        if (versionedLib == null) {
11076            versionedLib = new LongSparseArray<>();
11077            mSharedLibraries.put(name, versionedLib);
11078            if (type == SharedLibraryInfo.TYPE_STATIC) {
11079                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11080            }
11081        } else if (versionedLib.indexOfKey(version) >= 0) {
11082            return false;
11083        }
11084        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11085                version, type, declaringPackageName, declaringVersionCode);
11086        versionedLib.put(version, libEntry);
11087        return true;
11088    }
11089
11090    private boolean removeSharedLibraryLPw(String name, long version) {
11091        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11092        if (versionedLib == null) {
11093            return false;
11094        }
11095        final int libIdx = versionedLib.indexOfKey(version);
11096        if (libIdx < 0) {
11097            return false;
11098        }
11099        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11100        versionedLib.remove(version);
11101        if (versionedLib.size() <= 0) {
11102            mSharedLibraries.remove(name);
11103            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11104                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11105                        .getPackageName());
11106            }
11107        }
11108        return true;
11109    }
11110
11111    /**
11112     * Adds a scanned package to the system. When this method is finished, the package will
11113     * be available for query, resolution, etc...
11114     */
11115    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11116            UserHandle user, final @ScanFlags int scanFlags, boolean chatty) {
11117        final String pkgName = pkg.packageName;
11118        if (mCustomResolverComponentName != null &&
11119                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11120            setUpCustomResolverActivity(pkg);
11121        }
11122
11123        if (pkg.packageName.equals("android")) {
11124            synchronized (mPackages) {
11125                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11126                    // Set up information for our fall-back user intent resolution activity.
11127                    mPlatformPackage = pkg;
11128                    pkg.mVersionCode = mSdkVersion;
11129                    pkg.mVersionCodeMajor = 0;
11130                    mAndroidApplication = pkg.applicationInfo;
11131                    if (!mResolverReplaced) {
11132                        mResolveActivity.applicationInfo = mAndroidApplication;
11133                        mResolveActivity.name = ResolverActivity.class.getName();
11134                        mResolveActivity.packageName = mAndroidApplication.packageName;
11135                        mResolveActivity.processName = "system:ui";
11136                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11137                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11138                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11139                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11140                        mResolveActivity.exported = true;
11141                        mResolveActivity.enabled = true;
11142                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11143                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11144                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11145                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11146                                | ActivityInfo.CONFIG_ORIENTATION
11147                                | ActivityInfo.CONFIG_KEYBOARD
11148                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11149                        mResolveInfo.activityInfo = mResolveActivity;
11150                        mResolveInfo.priority = 0;
11151                        mResolveInfo.preferredOrder = 0;
11152                        mResolveInfo.match = 0;
11153                        mResolveComponentName = new ComponentName(
11154                                mAndroidApplication.packageName, mResolveActivity.name);
11155                    }
11156                }
11157            }
11158        }
11159
11160        ArrayList<PackageParser.Package> clientLibPkgs = null;
11161        // writer
11162        synchronized (mPackages) {
11163            boolean hasStaticSharedLibs = false;
11164
11165            // Any app can add new static shared libraries
11166            if (pkg.staticSharedLibName != null) {
11167                // Static shared libs don't allow renaming as they have synthetic package
11168                // names to allow install of multiple versions, so use name from manifest.
11169                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11170                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11171                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
11172                    hasStaticSharedLibs = true;
11173                } else {
11174                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11175                                + pkg.staticSharedLibName + " already exists; skipping");
11176                }
11177                // Static shared libs cannot be updated once installed since they
11178                // use synthetic package name which includes the version code, so
11179                // not need to update other packages's shared lib dependencies.
11180            }
11181
11182            if (!hasStaticSharedLibs
11183                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11184                // Only system apps can add new dynamic shared libraries.
11185                if (pkg.libraryNames != null) {
11186                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11187                        String name = pkg.libraryNames.get(i);
11188                        boolean allowed = false;
11189                        if (pkg.isUpdatedSystemApp()) {
11190                            // New library entries can only be added through the
11191                            // system image.  This is important to get rid of a lot
11192                            // of nasty edge cases: for example if we allowed a non-
11193                            // system update of the app to add a library, then uninstalling
11194                            // the update would make the library go away, and assumptions
11195                            // we made such as through app install filtering would now
11196                            // have allowed apps on the device which aren't compatible
11197                            // with it.  Better to just have the restriction here, be
11198                            // conservative, and create many fewer cases that can negatively
11199                            // impact the user experience.
11200                            final PackageSetting sysPs = mSettings
11201                                    .getDisabledSystemPkgLPr(pkg.packageName);
11202                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11203                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11204                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11205                                        allowed = true;
11206                                        break;
11207                                    }
11208                                }
11209                            }
11210                        } else {
11211                            allowed = true;
11212                        }
11213                        if (allowed) {
11214                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11215                                    SharedLibraryInfo.VERSION_UNDEFINED,
11216                                    SharedLibraryInfo.TYPE_DYNAMIC,
11217                                    pkg.packageName, pkg.getLongVersionCode())) {
11218                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11219                                        + name + " already exists; skipping");
11220                            }
11221                        } else {
11222                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11223                                    + name + " that is not declared on system image; skipping");
11224                        }
11225                    }
11226
11227                    if ((scanFlags & SCAN_BOOTING) == 0) {
11228                        // If we are not booting, we need to update any applications
11229                        // that are clients of our shared library.  If we are booting,
11230                        // this will all be done once the scan is complete.
11231                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11232                    }
11233                }
11234            }
11235        }
11236
11237        if ((scanFlags & SCAN_BOOTING) != 0) {
11238            // No apps can run during boot scan, so they don't need to be frozen
11239        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11240            // Caller asked to not kill app, so it's probably not frozen
11241        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11242            // Caller asked us to ignore frozen check for some reason; they
11243            // probably didn't know the package name
11244        } else {
11245            // We're doing major surgery on this package, so it better be frozen
11246            // right now to keep it from launching
11247            checkPackageFrozen(pkgName);
11248        }
11249
11250        // Also need to kill any apps that are dependent on the library.
11251        if (clientLibPkgs != null) {
11252            for (int i=0; i<clientLibPkgs.size(); i++) {
11253                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11254                killApplication(clientPkg.applicationInfo.packageName,
11255                        clientPkg.applicationInfo.uid, "update lib");
11256            }
11257        }
11258
11259        // writer
11260        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11261
11262        synchronized (mPackages) {
11263            // We don't expect installation to fail beyond this point
11264
11265            // Add the new setting to mSettings
11266            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11267            // Add the new setting to mPackages
11268            mPackages.put(pkg.applicationInfo.packageName, pkg);
11269            // Make sure we don't accidentally delete its data.
11270            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11271            while (iter.hasNext()) {
11272                PackageCleanItem item = iter.next();
11273                if (pkgName.equals(item.packageName)) {
11274                    iter.remove();
11275                }
11276            }
11277
11278            // Add the package's KeySets to the global KeySetManagerService
11279            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11280            ksms.addScannedPackageLPw(pkg);
11281
11282            int N = pkg.providers.size();
11283            StringBuilder r = null;
11284            int i;
11285            for (i=0; i<N; i++) {
11286                PackageParser.Provider p = pkg.providers.get(i);
11287                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11288                        p.info.processName);
11289                mProviders.addProvider(p);
11290                p.syncable = p.info.isSyncable;
11291                if (p.info.authority != null) {
11292                    String names[] = p.info.authority.split(";");
11293                    p.info.authority = null;
11294                    for (int j = 0; j < names.length; j++) {
11295                        if (j == 1 && p.syncable) {
11296                            // We only want the first authority for a provider to possibly be
11297                            // syncable, so if we already added this provider using a different
11298                            // authority clear the syncable flag. We copy the provider before
11299                            // changing it because the mProviders object contains a reference
11300                            // to a provider that we don't want to change.
11301                            // Only do this for the second authority since the resulting provider
11302                            // object can be the same for all future authorities for this provider.
11303                            p = new PackageParser.Provider(p);
11304                            p.syncable = false;
11305                        }
11306                        if (!mProvidersByAuthority.containsKey(names[j])) {
11307                            mProvidersByAuthority.put(names[j], p);
11308                            if (p.info.authority == null) {
11309                                p.info.authority = names[j];
11310                            } else {
11311                                p.info.authority = p.info.authority + ";" + names[j];
11312                            }
11313                            if (DEBUG_PACKAGE_SCANNING) {
11314                                if (chatty)
11315                                    Log.d(TAG, "Registered content provider: " + names[j]
11316                                            + ", className = " + p.info.name + ", isSyncable = "
11317                                            + p.info.isSyncable);
11318                            }
11319                        } else {
11320                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11321                            Slog.w(TAG, "Skipping provider name " + names[j] +
11322                                    " (in package " + pkg.applicationInfo.packageName +
11323                                    "): name already used by "
11324                                    + ((other != null && other.getComponentName() != null)
11325                                            ? other.getComponentName().getPackageName() : "?"));
11326                        }
11327                    }
11328                }
11329                if (chatty) {
11330                    if (r == null) {
11331                        r = new StringBuilder(256);
11332                    } else {
11333                        r.append(' ');
11334                    }
11335                    r.append(p.info.name);
11336                }
11337            }
11338            if (r != null) {
11339                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11340            }
11341
11342            N = pkg.services.size();
11343            r = null;
11344            for (i=0; i<N; i++) {
11345                PackageParser.Service s = pkg.services.get(i);
11346                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11347                        s.info.processName);
11348                mServices.addService(s);
11349                if (chatty) {
11350                    if (r == null) {
11351                        r = new StringBuilder(256);
11352                    } else {
11353                        r.append(' ');
11354                    }
11355                    r.append(s.info.name);
11356                }
11357            }
11358            if (r != null) {
11359                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11360            }
11361
11362            N = pkg.receivers.size();
11363            r = null;
11364            for (i=0; i<N; i++) {
11365                PackageParser.Activity a = pkg.receivers.get(i);
11366                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11367                        a.info.processName);
11368                mReceivers.addActivity(a, "receiver");
11369                if (chatty) {
11370                    if (r == null) {
11371                        r = new StringBuilder(256);
11372                    } else {
11373                        r.append(' ');
11374                    }
11375                    r.append(a.info.name);
11376                }
11377            }
11378            if (r != null) {
11379                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11380            }
11381
11382            N = pkg.activities.size();
11383            r = null;
11384            for (i=0; i<N; i++) {
11385                PackageParser.Activity a = pkg.activities.get(i);
11386                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11387                        a.info.processName);
11388                mActivities.addActivity(a, "activity");
11389                if (chatty) {
11390                    if (r == null) {
11391                        r = new StringBuilder(256);
11392                    } else {
11393                        r.append(' ');
11394                    }
11395                    r.append(a.info.name);
11396                }
11397            }
11398            if (r != null) {
11399                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11400            }
11401
11402            // Don't allow ephemeral applications to define new permissions groups.
11403            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11404                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11405                        + " ignored: instant apps cannot define new permission groups.");
11406            } else {
11407                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11408            }
11409
11410            // Don't allow ephemeral applications to define new permissions.
11411            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11412                Slog.w(TAG, "Permissions from package " + pkg.packageName
11413                        + " ignored: instant apps cannot define new permissions.");
11414            } else {
11415                mPermissionManager.addAllPermissions(pkg, chatty);
11416            }
11417
11418            N = pkg.instrumentation.size();
11419            r = null;
11420            for (i=0; i<N; i++) {
11421                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11422                a.info.packageName = pkg.applicationInfo.packageName;
11423                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11424                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11425                a.info.splitNames = pkg.splitNames;
11426                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11427                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11428                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11429                a.info.dataDir = pkg.applicationInfo.dataDir;
11430                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11431                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11432                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11433                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11434                mInstrumentation.put(a.getComponentName(), a);
11435                if (chatty) {
11436                    if (r == null) {
11437                        r = new StringBuilder(256);
11438                    } else {
11439                        r.append(' ');
11440                    }
11441                    r.append(a.info.name);
11442                }
11443            }
11444            if (r != null) {
11445                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11446            }
11447
11448            if (pkg.protectedBroadcasts != null) {
11449                N = pkg.protectedBroadcasts.size();
11450                synchronized (mProtectedBroadcasts) {
11451                    for (i = 0; i < N; i++) {
11452                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11453                    }
11454                }
11455            }
11456        }
11457
11458        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11459    }
11460
11461    /**
11462     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11463     * is derived purely on the basis of the contents of {@code scanFile} and
11464     * {@code cpuAbiOverride}.
11465     *
11466     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11467     */
11468    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11469            boolean extractLibs)
11470                    throws PackageManagerException {
11471        // Give ourselves some initial paths; we'll come back for another
11472        // pass once we've determined ABI below.
11473        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11474
11475        // We would never need to extract libs for forward-locked and external packages,
11476        // since the container service will do it for us. We shouldn't attempt to
11477        // extract libs from system app when it was not updated.
11478        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11479                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11480            extractLibs = false;
11481        }
11482
11483        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11484        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11485
11486        NativeLibraryHelper.Handle handle = null;
11487        try {
11488            handle = NativeLibraryHelper.Handle.create(pkg);
11489            // TODO(multiArch): This can be null for apps that didn't go through the
11490            // usual installation process. We can calculate it again, like we
11491            // do during install time.
11492            //
11493            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11494            // unnecessary.
11495            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11496
11497            // Null out the abis so that they can be recalculated.
11498            pkg.applicationInfo.primaryCpuAbi = null;
11499            pkg.applicationInfo.secondaryCpuAbi = null;
11500            if (isMultiArch(pkg.applicationInfo)) {
11501                // Warn if we've set an abiOverride for multi-lib packages..
11502                // By definition, we need to copy both 32 and 64 bit libraries for
11503                // such packages.
11504                if (pkg.cpuAbiOverride != null
11505                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11506                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11507                }
11508
11509                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11510                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11511                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11512                    if (extractLibs) {
11513                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11514                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11515                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11516                                useIsaSpecificSubdirs);
11517                    } else {
11518                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11519                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11520                    }
11521                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11522                }
11523
11524                // Shared library native code should be in the APK zip aligned
11525                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11526                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11527                            "Shared library native lib extraction not supported");
11528                }
11529
11530                maybeThrowExceptionForMultiArchCopy(
11531                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11532
11533                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11534                    if (extractLibs) {
11535                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11536                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11537                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11538                                useIsaSpecificSubdirs);
11539                    } else {
11540                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11541                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11542                    }
11543                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11544                }
11545
11546                maybeThrowExceptionForMultiArchCopy(
11547                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11548
11549                if (abi64 >= 0) {
11550                    // Shared library native libs should be in the APK zip aligned
11551                    if (extractLibs && pkg.isLibrary()) {
11552                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11553                                "Shared library native lib extraction not supported");
11554                    }
11555                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11556                }
11557
11558                if (abi32 >= 0) {
11559                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11560                    if (abi64 >= 0) {
11561                        if (pkg.use32bitAbi) {
11562                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11563                            pkg.applicationInfo.primaryCpuAbi = abi;
11564                        } else {
11565                            pkg.applicationInfo.secondaryCpuAbi = abi;
11566                        }
11567                    } else {
11568                        pkg.applicationInfo.primaryCpuAbi = abi;
11569                    }
11570                }
11571            } else {
11572                String[] abiList = (cpuAbiOverride != null) ?
11573                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11574
11575                // Enable gross and lame hacks for apps that are built with old
11576                // SDK tools. We must scan their APKs for renderscript bitcode and
11577                // not launch them if it's present. Don't bother checking on devices
11578                // that don't have 64 bit support.
11579                boolean needsRenderScriptOverride = false;
11580                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11581                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11582                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11583                    needsRenderScriptOverride = true;
11584                }
11585
11586                final int copyRet;
11587                if (extractLibs) {
11588                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11589                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11590                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11591                } else {
11592                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11593                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11594                }
11595                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11596
11597                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11598                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11599                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11600                }
11601
11602                if (copyRet >= 0) {
11603                    // Shared libraries that have native libs must be multi-architecture
11604                    if (pkg.isLibrary()) {
11605                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11606                                "Shared library with native libs must be multiarch");
11607                    }
11608                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11609                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11610                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11611                } else if (needsRenderScriptOverride) {
11612                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11613                }
11614            }
11615        } catch (IOException ioe) {
11616            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11617        } finally {
11618            IoUtils.closeQuietly(handle);
11619        }
11620
11621        // Now that we've calculated the ABIs and determined if it's an internal app,
11622        // we will go ahead and populate the nativeLibraryPath.
11623        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11624    }
11625
11626    /**
11627     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11628     * i.e, so that all packages can be run inside a single process if required.
11629     *
11630     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11631     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11632     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11633     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11634     * updating a package that belongs to a shared user.
11635     *
11636     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11637     * adds unnecessary complexity.
11638     */
11639    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11640            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11641        List<String> changedAbiCodePath = null;
11642        String requiredInstructionSet = null;
11643        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11644            requiredInstructionSet = VMRuntime.getInstructionSet(
11645                     scannedPackage.applicationInfo.primaryCpuAbi);
11646        }
11647
11648        PackageSetting requirer = null;
11649        for (PackageSetting ps : packagesForUser) {
11650            // If packagesForUser contains scannedPackage, we skip it. This will happen
11651            // when scannedPackage is an update of an existing package. Without this check,
11652            // we will never be able to change the ABI of any package belonging to a shared
11653            // user, even if it's compatible with other packages.
11654            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11655                if (ps.primaryCpuAbiString == null) {
11656                    continue;
11657                }
11658
11659                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11660                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11661                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11662                    // this but there's not much we can do.
11663                    String errorMessage = "Instruction set mismatch, "
11664                            + ((requirer == null) ? "[caller]" : requirer)
11665                            + " requires " + requiredInstructionSet + " whereas " + ps
11666                            + " requires " + instructionSet;
11667                    Slog.w(TAG, errorMessage);
11668                }
11669
11670                if (requiredInstructionSet == null) {
11671                    requiredInstructionSet = instructionSet;
11672                    requirer = ps;
11673                }
11674            }
11675        }
11676
11677        if (requiredInstructionSet != null) {
11678            String adjustedAbi;
11679            if (requirer != null) {
11680                // requirer != null implies that either scannedPackage was null or that scannedPackage
11681                // did not require an ABI, in which case we have to adjust scannedPackage to match
11682                // the ABI of the set (which is the same as requirer's ABI)
11683                adjustedAbi = requirer.primaryCpuAbiString;
11684                if (scannedPackage != null) {
11685                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11686                }
11687            } else {
11688                // requirer == null implies that we're updating all ABIs in the set to
11689                // match scannedPackage.
11690                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11691            }
11692
11693            for (PackageSetting ps : packagesForUser) {
11694                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11695                    if (ps.primaryCpuAbiString != null) {
11696                        continue;
11697                    }
11698
11699                    ps.primaryCpuAbiString = adjustedAbi;
11700                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11701                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11702                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11703                        if (DEBUG_ABI_SELECTION) {
11704                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11705                                    + " (requirer="
11706                                    + (requirer != null ? requirer.pkg : "null")
11707                                    + ", scannedPackage="
11708                                    + (scannedPackage != null ? scannedPackage : "null")
11709                                    + ")");
11710                        }
11711                        if (changedAbiCodePath == null) {
11712                            changedAbiCodePath = new ArrayList<>();
11713                        }
11714                        changedAbiCodePath.add(ps.codePathString);
11715                    }
11716                }
11717            }
11718        }
11719        return changedAbiCodePath;
11720    }
11721
11722    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11723        synchronized (mPackages) {
11724            mResolverReplaced = true;
11725            // Set up information for custom user intent resolution activity.
11726            mResolveActivity.applicationInfo = pkg.applicationInfo;
11727            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11728            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11729            mResolveActivity.processName = pkg.applicationInfo.packageName;
11730            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11731            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11732                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11733            mResolveActivity.theme = 0;
11734            mResolveActivity.exported = true;
11735            mResolveActivity.enabled = true;
11736            mResolveInfo.activityInfo = mResolveActivity;
11737            mResolveInfo.priority = 0;
11738            mResolveInfo.preferredOrder = 0;
11739            mResolveInfo.match = 0;
11740            mResolveComponentName = mCustomResolverComponentName;
11741            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11742                    mResolveComponentName);
11743        }
11744    }
11745
11746    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11747        if (installerActivity == null) {
11748            if (DEBUG_EPHEMERAL) {
11749                Slog.d(TAG, "Clear ephemeral installer activity");
11750            }
11751            mInstantAppInstallerActivity = null;
11752            return;
11753        }
11754
11755        if (DEBUG_EPHEMERAL) {
11756            Slog.d(TAG, "Set ephemeral installer activity: "
11757                    + installerActivity.getComponentName());
11758        }
11759        // Set up information for ephemeral installer activity
11760        mInstantAppInstallerActivity = installerActivity;
11761        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11762                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11763        mInstantAppInstallerActivity.exported = true;
11764        mInstantAppInstallerActivity.enabled = true;
11765        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11766        mInstantAppInstallerInfo.priority = 0;
11767        mInstantAppInstallerInfo.preferredOrder = 1;
11768        mInstantAppInstallerInfo.isDefault = true;
11769        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11770                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11771    }
11772
11773    private static String calculateBundledApkRoot(final String codePathString) {
11774        final File codePath = new File(codePathString);
11775        final File codeRoot;
11776        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11777            codeRoot = Environment.getRootDirectory();
11778        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11779            codeRoot = Environment.getOemDirectory();
11780        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11781            codeRoot = Environment.getVendorDirectory();
11782        } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) {
11783            codeRoot = Environment.getProductDirectory();
11784        } else {
11785            // Unrecognized code path; take its top real segment as the apk root:
11786            // e.g. /something/app/blah.apk => /something
11787            try {
11788                File f = codePath.getCanonicalFile();
11789                File parent = f.getParentFile();    // non-null because codePath is a file
11790                File tmp;
11791                while ((tmp = parent.getParentFile()) != null) {
11792                    f = parent;
11793                    parent = tmp;
11794                }
11795                codeRoot = f;
11796                Slog.w(TAG, "Unrecognized code path "
11797                        + codePath + " - using " + codeRoot);
11798            } catch (IOException e) {
11799                // Can't canonicalize the code path -- shenanigans?
11800                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11801                return Environment.getRootDirectory().getPath();
11802            }
11803        }
11804        return codeRoot.getPath();
11805    }
11806
11807    /**
11808     * Derive and set the location of native libraries for the given package,
11809     * which varies depending on where and how the package was installed.
11810     */
11811    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11812        final ApplicationInfo info = pkg.applicationInfo;
11813        final String codePath = pkg.codePath;
11814        final File codeFile = new File(codePath);
11815        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11816        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11817
11818        info.nativeLibraryRootDir = null;
11819        info.nativeLibraryRootRequiresIsa = false;
11820        info.nativeLibraryDir = null;
11821        info.secondaryNativeLibraryDir = null;
11822
11823        if (isApkFile(codeFile)) {
11824            // Monolithic install
11825            if (bundledApp) {
11826                // If "/system/lib64/apkname" exists, assume that is the per-package
11827                // native library directory to use; otherwise use "/system/lib/apkname".
11828                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11829                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11830                        getPrimaryInstructionSet(info));
11831
11832                // This is a bundled system app so choose the path based on the ABI.
11833                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11834                // is just the default path.
11835                final String apkName = deriveCodePathName(codePath);
11836                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11837                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11838                        apkName).getAbsolutePath();
11839
11840                if (info.secondaryCpuAbi != null) {
11841                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11842                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11843                            secondaryLibDir, apkName).getAbsolutePath();
11844                }
11845            } else if (asecApp) {
11846                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11847                        .getAbsolutePath();
11848            } else {
11849                final String apkName = deriveCodePathName(codePath);
11850                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11851                        .getAbsolutePath();
11852            }
11853
11854            info.nativeLibraryRootRequiresIsa = false;
11855            info.nativeLibraryDir = info.nativeLibraryRootDir;
11856        } else {
11857            // Cluster install
11858            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11859            info.nativeLibraryRootRequiresIsa = true;
11860
11861            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11862                    getPrimaryInstructionSet(info)).getAbsolutePath();
11863
11864            if (info.secondaryCpuAbi != null) {
11865                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11866                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11867            }
11868        }
11869    }
11870
11871    /**
11872     * Calculate the abis and roots for a bundled app. These can uniquely
11873     * be determined from the contents of the system partition, i.e whether
11874     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11875     * of this information, and instead assume that the system was built
11876     * sensibly.
11877     */
11878    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11879                                           PackageSetting pkgSetting) {
11880        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11881
11882        // If "/system/lib64/apkname" exists, assume that is the per-package
11883        // native library directory to use; otherwise use "/system/lib/apkname".
11884        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11885        setBundledAppAbi(pkg, apkRoot, apkName);
11886        // pkgSetting might be null during rescan following uninstall of updates
11887        // to a bundled app, so accommodate that possibility.  The settings in
11888        // that case will be established later from the parsed package.
11889        //
11890        // If the settings aren't null, sync them up with what we've just derived.
11891        // note that apkRoot isn't stored in the package settings.
11892        if (pkgSetting != null) {
11893            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11894            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11895        }
11896    }
11897
11898    /**
11899     * Deduces the ABI of a bundled app and sets the relevant fields on the
11900     * parsed pkg object.
11901     *
11902     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11903     *        under which system libraries are installed.
11904     * @param apkName the name of the installed package.
11905     */
11906    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11907        final File codeFile = new File(pkg.codePath);
11908
11909        final boolean has64BitLibs;
11910        final boolean has32BitLibs;
11911        if (isApkFile(codeFile)) {
11912            // Monolithic install
11913            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11914            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11915        } else {
11916            // Cluster install
11917            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11918            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11919                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11920                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11921                has64BitLibs = (new File(rootDir, isa)).exists();
11922            } else {
11923                has64BitLibs = false;
11924            }
11925            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11926                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11927                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11928                has32BitLibs = (new File(rootDir, isa)).exists();
11929            } else {
11930                has32BitLibs = false;
11931            }
11932        }
11933
11934        if (has64BitLibs && !has32BitLibs) {
11935            // The package has 64 bit libs, but not 32 bit libs. Its primary
11936            // ABI should be 64 bit. We can safely assume here that the bundled
11937            // native libraries correspond to the most preferred ABI in the list.
11938
11939            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11940            pkg.applicationInfo.secondaryCpuAbi = null;
11941        } else if (has32BitLibs && !has64BitLibs) {
11942            // The package has 32 bit libs but not 64 bit libs. Its primary
11943            // ABI should be 32 bit.
11944
11945            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11946            pkg.applicationInfo.secondaryCpuAbi = null;
11947        } else if (has32BitLibs && has64BitLibs) {
11948            // The application has both 64 and 32 bit bundled libraries. We check
11949            // here that the app declares multiArch support, and warn if it doesn't.
11950            //
11951            // We will be lenient here and record both ABIs. The primary will be the
11952            // ABI that's higher on the list, i.e, a device that's configured to prefer
11953            // 64 bit apps will see a 64 bit primary ABI,
11954
11955            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11956                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11957            }
11958
11959            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11960                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11961                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11962            } else {
11963                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11964                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11965            }
11966        } else {
11967            pkg.applicationInfo.primaryCpuAbi = null;
11968            pkg.applicationInfo.secondaryCpuAbi = null;
11969        }
11970    }
11971
11972    private void killApplication(String pkgName, int appId, String reason) {
11973        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11974    }
11975
11976    private void killApplication(String pkgName, int appId, int userId, String reason) {
11977        // Request the ActivityManager to kill the process(only for existing packages)
11978        // so that we do not end up in a confused state while the user is still using the older
11979        // version of the application while the new one gets installed.
11980        final long token = Binder.clearCallingIdentity();
11981        try {
11982            IActivityManager am = ActivityManager.getService();
11983            if (am != null) {
11984                try {
11985                    am.killApplication(pkgName, appId, userId, reason);
11986                } catch (RemoteException e) {
11987                }
11988            }
11989        } finally {
11990            Binder.restoreCallingIdentity(token);
11991        }
11992    }
11993
11994    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11995        // Remove the parent package setting
11996        PackageSetting ps = (PackageSetting) pkg.mExtras;
11997        if (ps != null) {
11998            removePackageLI(ps, chatty);
11999        }
12000        // Remove the child package setting
12001        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12002        for (int i = 0; i < childCount; i++) {
12003            PackageParser.Package childPkg = pkg.childPackages.get(i);
12004            ps = (PackageSetting) childPkg.mExtras;
12005            if (ps != null) {
12006                removePackageLI(ps, chatty);
12007            }
12008        }
12009    }
12010
12011    void removePackageLI(PackageSetting ps, boolean chatty) {
12012        if (DEBUG_INSTALL) {
12013            if (chatty)
12014                Log.d(TAG, "Removing package " + ps.name);
12015        }
12016
12017        // writer
12018        synchronized (mPackages) {
12019            mPackages.remove(ps.name);
12020            final PackageParser.Package pkg = ps.pkg;
12021            if (pkg != null) {
12022                cleanPackageDataStructuresLILPw(pkg, chatty);
12023            }
12024        }
12025    }
12026
12027    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12028        if (DEBUG_INSTALL) {
12029            if (chatty)
12030                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12031        }
12032
12033        // writer
12034        synchronized (mPackages) {
12035            // Remove the parent package
12036            mPackages.remove(pkg.applicationInfo.packageName);
12037            cleanPackageDataStructuresLILPw(pkg, chatty);
12038
12039            // Remove the child packages
12040            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12041            for (int i = 0; i < childCount; i++) {
12042                PackageParser.Package childPkg = pkg.childPackages.get(i);
12043                mPackages.remove(childPkg.applicationInfo.packageName);
12044                cleanPackageDataStructuresLILPw(childPkg, chatty);
12045            }
12046        }
12047    }
12048
12049    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12050        int N = pkg.providers.size();
12051        StringBuilder r = null;
12052        int i;
12053        for (i=0; i<N; i++) {
12054            PackageParser.Provider p = pkg.providers.get(i);
12055            mProviders.removeProvider(p);
12056            if (p.info.authority == null) {
12057
12058                /* There was another ContentProvider with this authority when
12059                 * this app was installed so this authority is null,
12060                 * Ignore it as we don't have to unregister the provider.
12061                 */
12062                continue;
12063            }
12064            String names[] = p.info.authority.split(";");
12065            for (int j = 0; j < names.length; j++) {
12066                if (mProvidersByAuthority.get(names[j]) == p) {
12067                    mProvidersByAuthority.remove(names[j]);
12068                    if (DEBUG_REMOVE) {
12069                        if (chatty)
12070                            Log.d(TAG, "Unregistered content provider: " + names[j]
12071                                    + ", className = " + p.info.name + ", isSyncable = "
12072                                    + p.info.isSyncable);
12073                    }
12074                }
12075            }
12076            if (DEBUG_REMOVE && chatty) {
12077                if (r == null) {
12078                    r = new StringBuilder(256);
12079                } else {
12080                    r.append(' ');
12081                }
12082                r.append(p.info.name);
12083            }
12084        }
12085        if (r != null) {
12086            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12087        }
12088
12089        N = pkg.services.size();
12090        r = null;
12091        for (i=0; i<N; i++) {
12092            PackageParser.Service s = pkg.services.get(i);
12093            mServices.removeService(s);
12094            if (chatty) {
12095                if (r == null) {
12096                    r = new StringBuilder(256);
12097                } else {
12098                    r.append(' ');
12099                }
12100                r.append(s.info.name);
12101            }
12102        }
12103        if (r != null) {
12104            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12105        }
12106
12107        N = pkg.receivers.size();
12108        r = null;
12109        for (i=0; i<N; i++) {
12110            PackageParser.Activity a = pkg.receivers.get(i);
12111            mReceivers.removeActivity(a, "receiver");
12112            if (DEBUG_REMOVE && chatty) {
12113                if (r == null) {
12114                    r = new StringBuilder(256);
12115                } else {
12116                    r.append(' ');
12117                }
12118                r.append(a.info.name);
12119            }
12120        }
12121        if (r != null) {
12122            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12123        }
12124
12125        N = pkg.activities.size();
12126        r = null;
12127        for (i=0; i<N; i++) {
12128            PackageParser.Activity a = pkg.activities.get(i);
12129            mActivities.removeActivity(a, "activity");
12130            if (DEBUG_REMOVE && chatty) {
12131                if (r == null) {
12132                    r = new StringBuilder(256);
12133                } else {
12134                    r.append(' ');
12135                }
12136                r.append(a.info.name);
12137            }
12138        }
12139        if (r != null) {
12140            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12141        }
12142
12143        mPermissionManager.removeAllPermissions(pkg, chatty);
12144
12145        N = pkg.instrumentation.size();
12146        r = null;
12147        for (i=0; i<N; i++) {
12148            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12149            mInstrumentation.remove(a.getComponentName());
12150            if (DEBUG_REMOVE && chatty) {
12151                if (r == null) {
12152                    r = new StringBuilder(256);
12153                } else {
12154                    r.append(' ');
12155                }
12156                r.append(a.info.name);
12157            }
12158        }
12159        if (r != null) {
12160            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12161        }
12162
12163        r = null;
12164        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12165            // Only system apps can hold shared libraries.
12166            if (pkg.libraryNames != null) {
12167                for (i = 0; i < pkg.libraryNames.size(); i++) {
12168                    String name = pkg.libraryNames.get(i);
12169                    if (removeSharedLibraryLPw(name, 0)) {
12170                        if (DEBUG_REMOVE && chatty) {
12171                            if (r == null) {
12172                                r = new StringBuilder(256);
12173                            } else {
12174                                r.append(' ');
12175                            }
12176                            r.append(name);
12177                        }
12178                    }
12179                }
12180            }
12181        }
12182
12183        r = null;
12184
12185        // Any package can hold static shared libraries.
12186        if (pkg.staticSharedLibName != null) {
12187            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12188                if (DEBUG_REMOVE && chatty) {
12189                    if (r == null) {
12190                        r = new StringBuilder(256);
12191                    } else {
12192                        r.append(' ');
12193                    }
12194                    r.append(pkg.staticSharedLibName);
12195                }
12196            }
12197        }
12198
12199        if (r != null) {
12200            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12201        }
12202    }
12203
12204
12205    final class ActivityIntentResolver
12206            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12207        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12208                boolean defaultOnly, int userId) {
12209            if (!sUserManager.exists(userId)) return null;
12210            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12211            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12212        }
12213
12214        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12215                int userId) {
12216            if (!sUserManager.exists(userId)) return null;
12217            mFlags = flags;
12218            return super.queryIntent(intent, resolvedType,
12219                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12220                    userId);
12221        }
12222
12223        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12224                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12225            if (!sUserManager.exists(userId)) return null;
12226            if (packageActivities == null) {
12227                return null;
12228            }
12229            mFlags = flags;
12230            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12231            final int N = packageActivities.size();
12232            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12233                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12234
12235            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12236            for (int i = 0; i < N; ++i) {
12237                intentFilters = packageActivities.get(i).intents;
12238                if (intentFilters != null && intentFilters.size() > 0) {
12239                    PackageParser.ActivityIntentInfo[] array =
12240                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12241                    intentFilters.toArray(array);
12242                    listCut.add(array);
12243                }
12244            }
12245            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12246        }
12247
12248        /**
12249         * Finds a privileged activity that matches the specified activity names.
12250         */
12251        private PackageParser.Activity findMatchingActivity(
12252                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12253            for (PackageParser.Activity sysActivity : activityList) {
12254                if (sysActivity.info.name.equals(activityInfo.name)) {
12255                    return sysActivity;
12256                }
12257                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12258                    return sysActivity;
12259                }
12260                if (sysActivity.info.targetActivity != null) {
12261                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12262                        return sysActivity;
12263                    }
12264                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12265                        return sysActivity;
12266                    }
12267                }
12268            }
12269            return null;
12270        }
12271
12272        public class IterGenerator<E> {
12273            public Iterator<E> generate(ActivityIntentInfo info) {
12274                return null;
12275            }
12276        }
12277
12278        public class ActionIterGenerator extends IterGenerator<String> {
12279            @Override
12280            public Iterator<String> generate(ActivityIntentInfo info) {
12281                return info.actionsIterator();
12282            }
12283        }
12284
12285        public class CategoriesIterGenerator extends IterGenerator<String> {
12286            @Override
12287            public Iterator<String> generate(ActivityIntentInfo info) {
12288                return info.categoriesIterator();
12289            }
12290        }
12291
12292        public class SchemesIterGenerator extends IterGenerator<String> {
12293            @Override
12294            public Iterator<String> generate(ActivityIntentInfo info) {
12295                return info.schemesIterator();
12296            }
12297        }
12298
12299        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12300            @Override
12301            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12302                return info.authoritiesIterator();
12303            }
12304        }
12305
12306        /**
12307         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12308         * MODIFIED. Do not pass in a list that should not be changed.
12309         */
12310        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12311                IterGenerator<T> generator, Iterator<T> searchIterator) {
12312            // loop through the set of actions; every one must be found in the intent filter
12313            while (searchIterator.hasNext()) {
12314                // we must have at least one filter in the list to consider a match
12315                if (intentList.size() == 0) {
12316                    break;
12317                }
12318
12319                final T searchAction = searchIterator.next();
12320
12321                // loop through the set of intent filters
12322                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12323                while (intentIter.hasNext()) {
12324                    final ActivityIntentInfo intentInfo = intentIter.next();
12325                    boolean selectionFound = false;
12326
12327                    // loop through the intent filter's selection criteria; at least one
12328                    // of them must match the searched criteria
12329                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12330                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12331                        final T intentSelection = intentSelectionIter.next();
12332                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12333                            selectionFound = true;
12334                            break;
12335                        }
12336                    }
12337
12338                    // the selection criteria wasn't found in this filter's set; this filter
12339                    // is not a potential match
12340                    if (!selectionFound) {
12341                        intentIter.remove();
12342                    }
12343                }
12344            }
12345        }
12346
12347        private boolean isProtectedAction(ActivityIntentInfo filter) {
12348            final Iterator<String> actionsIter = filter.actionsIterator();
12349            while (actionsIter != null && actionsIter.hasNext()) {
12350                final String filterAction = actionsIter.next();
12351                if (PROTECTED_ACTIONS.contains(filterAction)) {
12352                    return true;
12353                }
12354            }
12355            return false;
12356        }
12357
12358        /**
12359         * Adjusts the priority of the given intent filter according to policy.
12360         * <p>
12361         * <ul>
12362         * <li>The priority for non privileged applications is capped to '0'</li>
12363         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12364         * <li>The priority for unbundled updates to privileged applications is capped to the
12365         *      priority defined on the system partition</li>
12366         * </ul>
12367         * <p>
12368         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12369         * allowed to obtain any priority on any action.
12370         */
12371        private void adjustPriority(
12372                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12373            // nothing to do; priority is fine as-is
12374            if (intent.getPriority() <= 0) {
12375                return;
12376            }
12377
12378            final ActivityInfo activityInfo = intent.activity.info;
12379            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12380
12381            final boolean privilegedApp =
12382                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12383            if (!privilegedApp) {
12384                // non-privileged applications can never define a priority >0
12385                if (DEBUG_FILTERS) {
12386                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12387                            + " package: " + applicationInfo.packageName
12388                            + " activity: " + intent.activity.className
12389                            + " origPrio: " + intent.getPriority());
12390                }
12391                intent.setPriority(0);
12392                return;
12393            }
12394
12395            if (systemActivities == null) {
12396                // the system package is not disabled; we're parsing the system partition
12397                if (isProtectedAction(intent)) {
12398                    if (mDeferProtectedFilters) {
12399                        // We can't deal with these just yet. No component should ever obtain a
12400                        // >0 priority for a protected actions, with ONE exception -- the setup
12401                        // wizard. The setup wizard, however, cannot be known until we're able to
12402                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12403                        // until all intent filters have been processed. Chicken, meet egg.
12404                        // Let the filter temporarily have a high priority and rectify the
12405                        // priorities after all system packages have been scanned.
12406                        mProtectedFilters.add(intent);
12407                        if (DEBUG_FILTERS) {
12408                            Slog.i(TAG, "Protected action; save for later;"
12409                                    + " package: " + applicationInfo.packageName
12410                                    + " activity: " + intent.activity.className
12411                                    + " origPrio: " + intent.getPriority());
12412                        }
12413                        return;
12414                    } else {
12415                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12416                            Slog.i(TAG, "No setup wizard;"
12417                                + " All protected intents capped to priority 0");
12418                        }
12419                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12420                            if (DEBUG_FILTERS) {
12421                                Slog.i(TAG, "Found setup wizard;"
12422                                    + " allow priority " + intent.getPriority() + ";"
12423                                    + " package: " + intent.activity.info.packageName
12424                                    + " activity: " + intent.activity.className
12425                                    + " priority: " + intent.getPriority());
12426                            }
12427                            // setup wizard gets whatever it wants
12428                            return;
12429                        }
12430                        if (DEBUG_FILTERS) {
12431                            Slog.i(TAG, "Protected action; cap priority to 0;"
12432                                    + " package: " + intent.activity.info.packageName
12433                                    + " activity: " + intent.activity.className
12434                                    + " origPrio: " + intent.getPriority());
12435                        }
12436                        intent.setPriority(0);
12437                        return;
12438                    }
12439                }
12440                // privileged apps on the system image get whatever priority they request
12441                return;
12442            }
12443
12444            // privileged app unbundled update ... try to find the same activity
12445            final PackageParser.Activity foundActivity =
12446                    findMatchingActivity(systemActivities, activityInfo);
12447            if (foundActivity == null) {
12448                // this is a new activity; it cannot obtain >0 priority
12449                if (DEBUG_FILTERS) {
12450                    Slog.i(TAG, "New activity; cap priority to 0;"
12451                            + " package: " + applicationInfo.packageName
12452                            + " activity: " + intent.activity.className
12453                            + " origPrio: " + intent.getPriority());
12454                }
12455                intent.setPriority(0);
12456                return;
12457            }
12458
12459            // found activity, now check for filter equivalence
12460
12461            // a shallow copy is enough; we modify the list, not its contents
12462            final List<ActivityIntentInfo> intentListCopy =
12463                    new ArrayList<>(foundActivity.intents);
12464            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12465
12466            // find matching action subsets
12467            final Iterator<String> actionsIterator = intent.actionsIterator();
12468            if (actionsIterator != null) {
12469                getIntentListSubset(
12470                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12471                if (intentListCopy.size() == 0) {
12472                    // no more intents to match; we're not equivalent
12473                    if (DEBUG_FILTERS) {
12474                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12475                                + " package: " + applicationInfo.packageName
12476                                + " activity: " + intent.activity.className
12477                                + " origPrio: " + intent.getPriority());
12478                    }
12479                    intent.setPriority(0);
12480                    return;
12481                }
12482            }
12483
12484            // find matching category subsets
12485            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12486            if (categoriesIterator != null) {
12487                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12488                        categoriesIterator);
12489                if (intentListCopy.size() == 0) {
12490                    // no more intents to match; we're not equivalent
12491                    if (DEBUG_FILTERS) {
12492                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12493                                + " package: " + applicationInfo.packageName
12494                                + " activity: " + intent.activity.className
12495                                + " origPrio: " + intent.getPriority());
12496                    }
12497                    intent.setPriority(0);
12498                    return;
12499                }
12500            }
12501
12502            // find matching schemes subsets
12503            final Iterator<String> schemesIterator = intent.schemesIterator();
12504            if (schemesIterator != null) {
12505                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12506                        schemesIterator);
12507                if (intentListCopy.size() == 0) {
12508                    // no more intents to match; we're not equivalent
12509                    if (DEBUG_FILTERS) {
12510                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12511                                + " package: " + applicationInfo.packageName
12512                                + " activity: " + intent.activity.className
12513                                + " origPrio: " + intent.getPriority());
12514                    }
12515                    intent.setPriority(0);
12516                    return;
12517                }
12518            }
12519
12520            // find matching authorities subsets
12521            final Iterator<IntentFilter.AuthorityEntry>
12522                    authoritiesIterator = intent.authoritiesIterator();
12523            if (authoritiesIterator != null) {
12524                getIntentListSubset(intentListCopy,
12525                        new AuthoritiesIterGenerator(),
12526                        authoritiesIterator);
12527                if (intentListCopy.size() == 0) {
12528                    // no more intents to match; we're not equivalent
12529                    if (DEBUG_FILTERS) {
12530                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12531                                + " package: " + applicationInfo.packageName
12532                                + " activity: " + intent.activity.className
12533                                + " origPrio: " + intent.getPriority());
12534                    }
12535                    intent.setPriority(0);
12536                    return;
12537                }
12538            }
12539
12540            // we found matching filter(s); app gets the max priority of all intents
12541            int cappedPriority = 0;
12542            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12543                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12544            }
12545            if (intent.getPriority() > cappedPriority) {
12546                if (DEBUG_FILTERS) {
12547                    Slog.i(TAG, "Found matching filter(s);"
12548                            + " cap priority to " + cappedPriority + ";"
12549                            + " package: " + applicationInfo.packageName
12550                            + " activity: " + intent.activity.className
12551                            + " origPrio: " + intent.getPriority());
12552                }
12553                intent.setPriority(cappedPriority);
12554                return;
12555            }
12556            // all this for nothing; the requested priority was <= what was on the system
12557        }
12558
12559        public final void addActivity(PackageParser.Activity a, String type) {
12560            mActivities.put(a.getComponentName(), a);
12561            if (DEBUG_SHOW_INFO)
12562                Log.v(
12563                TAG, "  " + type + " " +
12564                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12565            if (DEBUG_SHOW_INFO)
12566                Log.v(TAG, "    Class=" + a.info.name);
12567            final int NI = a.intents.size();
12568            for (int j=0; j<NI; j++) {
12569                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12570                if ("activity".equals(type)) {
12571                    final PackageSetting ps =
12572                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12573                    final List<PackageParser.Activity> systemActivities =
12574                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12575                    adjustPriority(systemActivities, intent);
12576                }
12577                if (DEBUG_SHOW_INFO) {
12578                    Log.v(TAG, "    IntentFilter:");
12579                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12580                }
12581                if (!intent.debugCheck()) {
12582                    Log.w(TAG, "==> For Activity " + a.info.name);
12583                }
12584                addFilter(intent);
12585            }
12586        }
12587
12588        public final void removeActivity(PackageParser.Activity a, String type) {
12589            mActivities.remove(a.getComponentName());
12590            if (DEBUG_SHOW_INFO) {
12591                Log.v(TAG, "  " + type + " "
12592                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12593                                : a.info.name) + ":");
12594                Log.v(TAG, "    Class=" + a.info.name);
12595            }
12596            final int NI = a.intents.size();
12597            for (int j=0; j<NI; j++) {
12598                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12599                if (DEBUG_SHOW_INFO) {
12600                    Log.v(TAG, "    IntentFilter:");
12601                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12602                }
12603                removeFilter(intent);
12604            }
12605        }
12606
12607        @Override
12608        protected boolean allowFilterResult(
12609                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12610            ActivityInfo filterAi = filter.activity.info;
12611            for (int i=dest.size()-1; i>=0; i--) {
12612                ActivityInfo destAi = dest.get(i).activityInfo;
12613                if (destAi.name == filterAi.name
12614                        && destAi.packageName == filterAi.packageName) {
12615                    return false;
12616                }
12617            }
12618            return true;
12619        }
12620
12621        @Override
12622        protected ActivityIntentInfo[] newArray(int size) {
12623            return new ActivityIntentInfo[size];
12624        }
12625
12626        @Override
12627        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12628            if (!sUserManager.exists(userId)) return true;
12629            PackageParser.Package p = filter.activity.owner;
12630            if (p != null) {
12631                PackageSetting ps = (PackageSetting)p.mExtras;
12632                if (ps != null) {
12633                    // System apps are never considered stopped for purposes of
12634                    // filtering, because there may be no way for the user to
12635                    // actually re-launch them.
12636                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12637                            && ps.getStopped(userId);
12638                }
12639            }
12640            return false;
12641        }
12642
12643        @Override
12644        protected boolean isPackageForFilter(String packageName,
12645                PackageParser.ActivityIntentInfo info) {
12646            return packageName.equals(info.activity.owner.packageName);
12647        }
12648
12649        @Override
12650        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12651                int match, int userId) {
12652            if (!sUserManager.exists(userId)) return null;
12653            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12654                return null;
12655            }
12656            final PackageParser.Activity activity = info.activity;
12657            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12658            if (ps == null) {
12659                return null;
12660            }
12661            final PackageUserState userState = ps.readUserState(userId);
12662            ActivityInfo ai =
12663                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12664            if (ai == null) {
12665                return null;
12666            }
12667            final boolean matchExplicitlyVisibleOnly =
12668                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12669            final boolean matchVisibleToInstantApp =
12670                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12671            final boolean componentVisible =
12672                    matchVisibleToInstantApp
12673                    && info.isVisibleToInstantApp()
12674                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12675            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12676            // throw out filters that aren't visible to ephemeral apps
12677            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12678                return null;
12679            }
12680            // throw out instant app filters if we're not explicitly requesting them
12681            if (!matchInstantApp && userState.instantApp) {
12682                return null;
12683            }
12684            // throw out instant app filters if updates are available; will trigger
12685            // instant app resolution
12686            if (userState.instantApp && ps.isUpdateAvailable()) {
12687                return null;
12688            }
12689            final ResolveInfo res = new ResolveInfo();
12690            res.activityInfo = ai;
12691            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12692                res.filter = info;
12693            }
12694            if (info != null) {
12695                res.handleAllWebDataURI = info.handleAllWebDataURI();
12696            }
12697            res.priority = info.getPriority();
12698            res.preferredOrder = activity.owner.mPreferredOrder;
12699            //System.out.println("Result: " + res.activityInfo.className +
12700            //                   " = " + res.priority);
12701            res.match = match;
12702            res.isDefault = info.hasDefault;
12703            res.labelRes = info.labelRes;
12704            res.nonLocalizedLabel = info.nonLocalizedLabel;
12705            if (userNeedsBadging(userId)) {
12706                res.noResourceId = true;
12707            } else {
12708                res.icon = info.icon;
12709            }
12710            res.iconResourceId = info.icon;
12711            res.system = res.activityInfo.applicationInfo.isSystemApp();
12712            res.isInstantAppAvailable = userState.instantApp;
12713            return res;
12714        }
12715
12716        @Override
12717        protected void sortResults(List<ResolveInfo> results) {
12718            Collections.sort(results, mResolvePrioritySorter);
12719        }
12720
12721        @Override
12722        protected void dumpFilter(PrintWriter out, String prefix,
12723                PackageParser.ActivityIntentInfo filter) {
12724            out.print(prefix); out.print(
12725                    Integer.toHexString(System.identityHashCode(filter.activity)));
12726                    out.print(' ');
12727                    filter.activity.printComponentShortName(out);
12728                    out.print(" filter ");
12729                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12730        }
12731
12732        @Override
12733        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12734            return filter.activity;
12735        }
12736
12737        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12738            PackageParser.Activity activity = (PackageParser.Activity)label;
12739            out.print(prefix); out.print(
12740                    Integer.toHexString(System.identityHashCode(activity)));
12741                    out.print(' ');
12742                    activity.printComponentShortName(out);
12743            if (count > 1) {
12744                out.print(" ("); out.print(count); out.print(" filters)");
12745            }
12746            out.println();
12747        }
12748
12749        // Keys are String (activity class name), values are Activity.
12750        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12751                = new ArrayMap<ComponentName, PackageParser.Activity>();
12752        private int mFlags;
12753    }
12754
12755    private final class ServiceIntentResolver
12756            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12757        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12758                boolean defaultOnly, int userId) {
12759            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12760            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12761        }
12762
12763        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12764                int userId) {
12765            if (!sUserManager.exists(userId)) return null;
12766            mFlags = flags;
12767            return super.queryIntent(intent, resolvedType,
12768                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12769                    userId);
12770        }
12771
12772        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12773                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12774            if (!sUserManager.exists(userId)) return null;
12775            if (packageServices == null) {
12776                return null;
12777            }
12778            mFlags = flags;
12779            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12780            final int N = packageServices.size();
12781            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12782                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12783
12784            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12785            for (int i = 0; i < N; ++i) {
12786                intentFilters = packageServices.get(i).intents;
12787                if (intentFilters != null && intentFilters.size() > 0) {
12788                    PackageParser.ServiceIntentInfo[] array =
12789                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12790                    intentFilters.toArray(array);
12791                    listCut.add(array);
12792                }
12793            }
12794            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12795        }
12796
12797        public final void addService(PackageParser.Service s) {
12798            mServices.put(s.getComponentName(), s);
12799            if (DEBUG_SHOW_INFO) {
12800                Log.v(TAG, "  "
12801                        + (s.info.nonLocalizedLabel != null
12802                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12803                Log.v(TAG, "    Class=" + s.info.name);
12804            }
12805            final int NI = s.intents.size();
12806            int j;
12807            for (j=0; j<NI; j++) {
12808                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12809                if (DEBUG_SHOW_INFO) {
12810                    Log.v(TAG, "    IntentFilter:");
12811                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12812                }
12813                if (!intent.debugCheck()) {
12814                    Log.w(TAG, "==> For Service " + s.info.name);
12815                }
12816                addFilter(intent);
12817            }
12818        }
12819
12820        public final void removeService(PackageParser.Service s) {
12821            mServices.remove(s.getComponentName());
12822            if (DEBUG_SHOW_INFO) {
12823                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12824                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12825                Log.v(TAG, "    Class=" + s.info.name);
12826            }
12827            final int NI = s.intents.size();
12828            int j;
12829            for (j=0; j<NI; j++) {
12830                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12831                if (DEBUG_SHOW_INFO) {
12832                    Log.v(TAG, "    IntentFilter:");
12833                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12834                }
12835                removeFilter(intent);
12836            }
12837        }
12838
12839        @Override
12840        protected boolean allowFilterResult(
12841                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12842            ServiceInfo filterSi = filter.service.info;
12843            for (int i=dest.size()-1; i>=0; i--) {
12844                ServiceInfo destAi = dest.get(i).serviceInfo;
12845                if (destAi.name == filterSi.name
12846                        && destAi.packageName == filterSi.packageName) {
12847                    return false;
12848                }
12849            }
12850            return true;
12851        }
12852
12853        @Override
12854        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12855            return new PackageParser.ServiceIntentInfo[size];
12856        }
12857
12858        @Override
12859        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12860            if (!sUserManager.exists(userId)) return true;
12861            PackageParser.Package p = filter.service.owner;
12862            if (p != null) {
12863                PackageSetting ps = (PackageSetting)p.mExtras;
12864                if (ps != null) {
12865                    // System apps are never considered stopped for purposes of
12866                    // filtering, because there may be no way for the user to
12867                    // actually re-launch them.
12868                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12869                            && ps.getStopped(userId);
12870                }
12871            }
12872            return false;
12873        }
12874
12875        @Override
12876        protected boolean isPackageForFilter(String packageName,
12877                PackageParser.ServiceIntentInfo info) {
12878            return packageName.equals(info.service.owner.packageName);
12879        }
12880
12881        @Override
12882        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12883                int match, int userId) {
12884            if (!sUserManager.exists(userId)) return null;
12885            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12886            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12887                return null;
12888            }
12889            final PackageParser.Service service = info.service;
12890            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12891            if (ps == null) {
12892                return null;
12893            }
12894            final PackageUserState userState = ps.readUserState(userId);
12895            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12896                    userState, userId);
12897            if (si == null) {
12898                return null;
12899            }
12900            final boolean matchVisibleToInstantApp =
12901                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12902            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12903            // throw out filters that aren't visible to ephemeral apps
12904            if (matchVisibleToInstantApp
12905                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12906                return null;
12907            }
12908            // throw out ephemeral filters if we're not explicitly requesting them
12909            if (!isInstantApp && userState.instantApp) {
12910                return null;
12911            }
12912            // throw out instant app filters if updates are available; will trigger
12913            // instant app resolution
12914            if (userState.instantApp && ps.isUpdateAvailable()) {
12915                return null;
12916            }
12917            final ResolveInfo res = new ResolveInfo();
12918            res.serviceInfo = si;
12919            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12920                res.filter = filter;
12921            }
12922            res.priority = info.getPriority();
12923            res.preferredOrder = service.owner.mPreferredOrder;
12924            res.match = match;
12925            res.isDefault = info.hasDefault;
12926            res.labelRes = info.labelRes;
12927            res.nonLocalizedLabel = info.nonLocalizedLabel;
12928            res.icon = info.icon;
12929            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12930            return res;
12931        }
12932
12933        @Override
12934        protected void sortResults(List<ResolveInfo> results) {
12935            Collections.sort(results, mResolvePrioritySorter);
12936        }
12937
12938        @Override
12939        protected void dumpFilter(PrintWriter out, String prefix,
12940                PackageParser.ServiceIntentInfo filter) {
12941            out.print(prefix); out.print(
12942                    Integer.toHexString(System.identityHashCode(filter.service)));
12943                    out.print(' ');
12944                    filter.service.printComponentShortName(out);
12945                    out.print(" filter ");
12946                    out.print(Integer.toHexString(System.identityHashCode(filter)));
12947                    if (filter.service.info.permission != null) {
12948                        out.print(" permission "); out.println(filter.service.info.permission);
12949                    } else {
12950                        out.println();
12951                    }
12952        }
12953
12954        @Override
12955        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12956            return filter.service;
12957        }
12958
12959        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12960            PackageParser.Service service = (PackageParser.Service)label;
12961            out.print(prefix); out.print(
12962                    Integer.toHexString(System.identityHashCode(service)));
12963                    out.print(' ');
12964                    service.printComponentShortName(out);
12965            if (count > 1) {
12966                out.print(" ("); out.print(count); out.print(" filters)");
12967            }
12968            out.println();
12969        }
12970
12971//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12972//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12973//            final List<ResolveInfo> retList = Lists.newArrayList();
12974//            while (i.hasNext()) {
12975//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12976//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12977//                    retList.add(resolveInfo);
12978//                }
12979//            }
12980//            return retList;
12981//        }
12982
12983        // Keys are String (activity class name), values are Activity.
12984        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12985                = new ArrayMap<ComponentName, PackageParser.Service>();
12986        private int mFlags;
12987    }
12988
12989    private final class ProviderIntentResolver
12990            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12991        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12992                boolean defaultOnly, int userId) {
12993            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12994            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12995        }
12996
12997        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12998                int userId) {
12999            if (!sUserManager.exists(userId))
13000                return null;
13001            mFlags = flags;
13002            return super.queryIntent(intent, resolvedType,
13003                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13004                    userId);
13005        }
13006
13007        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13008                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13009            if (!sUserManager.exists(userId))
13010                return null;
13011            if (packageProviders == null) {
13012                return null;
13013            }
13014            mFlags = flags;
13015            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13016            final int N = packageProviders.size();
13017            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13018                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13019
13020            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13021            for (int i = 0; i < N; ++i) {
13022                intentFilters = packageProviders.get(i).intents;
13023                if (intentFilters != null && intentFilters.size() > 0) {
13024                    PackageParser.ProviderIntentInfo[] array =
13025                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13026                    intentFilters.toArray(array);
13027                    listCut.add(array);
13028                }
13029            }
13030            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13031        }
13032
13033        public final void addProvider(PackageParser.Provider p) {
13034            if (mProviders.containsKey(p.getComponentName())) {
13035                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13036                return;
13037            }
13038
13039            mProviders.put(p.getComponentName(), p);
13040            if (DEBUG_SHOW_INFO) {
13041                Log.v(TAG, "  "
13042                        + (p.info.nonLocalizedLabel != null
13043                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13044                Log.v(TAG, "    Class=" + p.info.name);
13045            }
13046            final int NI = p.intents.size();
13047            int j;
13048            for (j = 0; j < NI; j++) {
13049                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13050                if (DEBUG_SHOW_INFO) {
13051                    Log.v(TAG, "    IntentFilter:");
13052                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13053                }
13054                if (!intent.debugCheck()) {
13055                    Log.w(TAG, "==> For Provider " + p.info.name);
13056                }
13057                addFilter(intent);
13058            }
13059        }
13060
13061        public final void removeProvider(PackageParser.Provider p) {
13062            mProviders.remove(p.getComponentName());
13063            if (DEBUG_SHOW_INFO) {
13064                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13065                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13066                Log.v(TAG, "    Class=" + p.info.name);
13067            }
13068            final int NI = p.intents.size();
13069            int j;
13070            for (j = 0; j < NI; j++) {
13071                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13072                if (DEBUG_SHOW_INFO) {
13073                    Log.v(TAG, "    IntentFilter:");
13074                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13075                }
13076                removeFilter(intent);
13077            }
13078        }
13079
13080        @Override
13081        protected boolean allowFilterResult(
13082                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13083            ProviderInfo filterPi = filter.provider.info;
13084            for (int i = dest.size() - 1; i >= 0; i--) {
13085                ProviderInfo destPi = dest.get(i).providerInfo;
13086                if (destPi.name == filterPi.name
13087                        && destPi.packageName == filterPi.packageName) {
13088                    return false;
13089                }
13090            }
13091            return true;
13092        }
13093
13094        @Override
13095        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13096            return new PackageParser.ProviderIntentInfo[size];
13097        }
13098
13099        @Override
13100        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13101            if (!sUserManager.exists(userId))
13102                return true;
13103            PackageParser.Package p = filter.provider.owner;
13104            if (p != null) {
13105                PackageSetting ps = (PackageSetting) p.mExtras;
13106                if (ps != null) {
13107                    // System apps are never considered stopped for purposes of
13108                    // filtering, because there may be no way for the user to
13109                    // actually re-launch them.
13110                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13111                            && ps.getStopped(userId);
13112                }
13113            }
13114            return false;
13115        }
13116
13117        @Override
13118        protected boolean isPackageForFilter(String packageName,
13119                PackageParser.ProviderIntentInfo info) {
13120            return packageName.equals(info.provider.owner.packageName);
13121        }
13122
13123        @Override
13124        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13125                int match, int userId) {
13126            if (!sUserManager.exists(userId))
13127                return null;
13128            final PackageParser.ProviderIntentInfo info = filter;
13129            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13130                return null;
13131            }
13132            final PackageParser.Provider provider = info.provider;
13133            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13134            if (ps == null) {
13135                return null;
13136            }
13137            final PackageUserState userState = ps.readUserState(userId);
13138            final boolean matchVisibleToInstantApp =
13139                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13140            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13141            // throw out filters that aren't visible to instant applications
13142            if (matchVisibleToInstantApp
13143                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13144                return null;
13145            }
13146            // throw out instant application filters if we're not explicitly requesting them
13147            if (!isInstantApp && userState.instantApp) {
13148                return null;
13149            }
13150            // throw out instant application filters if updates are available; will trigger
13151            // instant application resolution
13152            if (userState.instantApp && ps.isUpdateAvailable()) {
13153                return null;
13154            }
13155            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13156                    userState, userId);
13157            if (pi == null) {
13158                return null;
13159            }
13160            final ResolveInfo res = new ResolveInfo();
13161            res.providerInfo = pi;
13162            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13163                res.filter = filter;
13164            }
13165            res.priority = info.getPriority();
13166            res.preferredOrder = provider.owner.mPreferredOrder;
13167            res.match = match;
13168            res.isDefault = info.hasDefault;
13169            res.labelRes = info.labelRes;
13170            res.nonLocalizedLabel = info.nonLocalizedLabel;
13171            res.icon = info.icon;
13172            res.system = res.providerInfo.applicationInfo.isSystemApp();
13173            return res;
13174        }
13175
13176        @Override
13177        protected void sortResults(List<ResolveInfo> results) {
13178            Collections.sort(results, mResolvePrioritySorter);
13179        }
13180
13181        @Override
13182        protected void dumpFilter(PrintWriter out, String prefix,
13183                PackageParser.ProviderIntentInfo filter) {
13184            out.print(prefix);
13185            out.print(
13186                    Integer.toHexString(System.identityHashCode(filter.provider)));
13187            out.print(' ');
13188            filter.provider.printComponentShortName(out);
13189            out.print(" filter ");
13190            out.println(Integer.toHexString(System.identityHashCode(filter)));
13191        }
13192
13193        @Override
13194        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13195            return filter.provider;
13196        }
13197
13198        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13199            PackageParser.Provider provider = (PackageParser.Provider)label;
13200            out.print(prefix); out.print(
13201                    Integer.toHexString(System.identityHashCode(provider)));
13202                    out.print(' ');
13203                    provider.printComponentShortName(out);
13204            if (count > 1) {
13205                out.print(" ("); out.print(count); out.print(" filters)");
13206            }
13207            out.println();
13208        }
13209
13210        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13211                = new ArrayMap<ComponentName, PackageParser.Provider>();
13212        private int mFlags;
13213    }
13214
13215    static final class EphemeralIntentResolver
13216            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13217        /**
13218         * The result that has the highest defined order. Ordering applies on a
13219         * per-package basis. Mapping is from package name to Pair of order and
13220         * EphemeralResolveInfo.
13221         * <p>
13222         * NOTE: This is implemented as a field variable for convenience and efficiency.
13223         * By having a field variable, we're able to track filter ordering as soon as
13224         * a non-zero order is defined. Otherwise, multiple loops across the result set
13225         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13226         * this needs to be contained entirely within {@link #filterResults}.
13227         */
13228        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13229
13230        @Override
13231        protected AuxiliaryResolveInfo[] newArray(int size) {
13232            return new AuxiliaryResolveInfo[size];
13233        }
13234
13235        @Override
13236        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13237            return true;
13238        }
13239
13240        @Override
13241        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13242                int userId) {
13243            if (!sUserManager.exists(userId)) {
13244                return null;
13245            }
13246            final String packageName = responseObj.resolveInfo.getPackageName();
13247            final Integer order = responseObj.getOrder();
13248            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13249                    mOrderResult.get(packageName);
13250            // ordering is enabled and this item's order isn't high enough
13251            if (lastOrderResult != null && lastOrderResult.first >= order) {
13252                return null;
13253            }
13254            final InstantAppResolveInfo res = responseObj.resolveInfo;
13255            if (order > 0) {
13256                // non-zero order, enable ordering
13257                mOrderResult.put(packageName, new Pair<>(order, res));
13258            }
13259            return responseObj;
13260        }
13261
13262        @Override
13263        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13264            // only do work if ordering is enabled [most of the time it won't be]
13265            if (mOrderResult.size() == 0) {
13266                return;
13267            }
13268            int resultSize = results.size();
13269            for (int i = 0; i < resultSize; i++) {
13270                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13271                final String packageName = info.getPackageName();
13272                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13273                if (savedInfo == null) {
13274                    // package doesn't having ordering
13275                    continue;
13276                }
13277                if (savedInfo.second == info) {
13278                    // circled back to the highest ordered item; remove from order list
13279                    mOrderResult.remove(packageName);
13280                    if (mOrderResult.size() == 0) {
13281                        // no more ordered items
13282                        break;
13283                    }
13284                    continue;
13285                }
13286                // item has a worse order, remove it from the result list
13287                results.remove(i);
13288                resultSize--;
13289                i--;
13290            }
13291        }
13292    }
13293
13294    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13295            new Comparator<ResolveInfo>() {
13296        public int compare(ResolveInfo r1, ResolveInfo r2) {
13297            int v1 = r1.priority;
13298            int v2 = r2.priority;
13299            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13300            if (v1 != v2) {
13301                return (v1 > v2) ? -1 : 1;
13302            }
13303            v1 = r1.preferredOrder;
13304            v2 = r2.preferredOrder;
13305            if (v1 != v2) {
13306                return (v1 > v2) ? -1 : 1;
13307            }
13308            if (r1.isDefault != r2.isDefault) {
13309                return r1.isDefault ? -1 : 1;
13310            }
13311            v1 = r1.match;
13312            v2 = r2.match;
13313            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13314            if (v1 != v2) {
13315                return (v1 > v2) ? -1 : 1;
13316            }
13317            if (r1.system != r2.system) {
13318                return r1.system ? -1 : 1;
13319            }
13320            if (r1.activityInfo != null) {
13321                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13322            }
13323            if (r1.serviceInfo != null) {
13324                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13325            }
13326            if (r1.providerInfo != null) {
13327                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13328            }
13329            return 0;
13330        }
13331    };
13332
13333    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13334            new Comparator<ProviderInfo>() {
13335        public int compare(ProviderInfo p1, ProviderInfo p2) {
13336            final int v1 = p1.initOrder;
13337            final int v2 = p2.initOrder;
13338            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13339        }
13340    };
13341
13342    @Override
13343    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13344            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13345            final int[] userIds, int[] instantUserIds) {
13346        mHandler.post(new Runnable() {
13347            @Override
13348            public void run() {
13349                try {
13350                    final IActivityManager am = ActivityManager.getService();
13351                    if (am == null) return;
13352                    final int[] resolvedUserIds;
13353                    if (userIds == null) {
13354                        resolvedUserIds = am.getRunningUserIds();
13355                    } else {
13356                        resolvedUserIds = userIds;
13357                    }
13358                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13359                            resolvedUserIds, false);
13360                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
13361                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13362                                instantUserIds, true);
13363                    }
13364                } catch (RemoteException ex) {
13365                }
13366            }
13367        });
13368    }
13369
13370    @Override
13371    public void notifyPackageAdded(String packageName) {
13372        final PackageListObserver[] observers;
13373        synchronized (mPackages) {
13374            if (mPackageListObservers.size() == 0) {
13375                return;
13376            }
13377            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13378        }
13379        for (int i = observers.length - 1; i >= 0; --i) {
13380            observers[i].onPackageAdded(packageName);
13381        }
13382    }
13383
13384    @Override
13385    public void notifyPackageRemoved(String packageName) {
13386        final PackageListObserver[] observers;
13387        synchronized (mPackages) {
13388            if (mPackageListObservers.size() == 0) {
13389                return;
13390            }
13391            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13392        }
13393        for (int i = observers.length - 1; i >= 0; --i) {
13394            observers[i].onPackageRemoved(packageName);
13395        }
13396    }
13397
13398    /**
13399     * Sends a broadcast for the given action.
13400     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13401     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13402     * the system and applications allowed to see instant applications to receive package
13403     * lifecycle events for instant applications.
13404     */
13405    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13406            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13407            int[] userIds, boolean isInstantApp)
13408                    throws RemoteException {
13409        for (int id : userIds) {
13410            final Intent intent = new Intent(action,
13411                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13412            final String[] requiredPermissions =
13413                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13414            if (extras != null) {
13415                intent.putExtras(extras);
13416            }
13417            if (targetPkg != null) {
13418                intent.setPackage(targetPkg);
13419            }
13420            // Modify the UID when posting to other users
13421            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13422            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13423                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13424                intent.putExtra(Intent.EXTRA_UID, uid);
13425            }
13426            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13427            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13428            if (DEBUG_BROADCASTS) {
13429                RuntimeException here = new RuntimeException("here");
13430                here.fillInStackTrace();
13431                Slog.d(TAG, "Sending to user " + id + ": "
13432                        + intent.toShortString(false, true, false, false)
13433                        + " " + intent.getExtras(), here);
13434            }
13435            am.broadcastIntent(null, intent, null, finishedReceiver,
13436                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13437                    null, finishedReceiver != null, false, id);
13438        }
13439    }
13440
13441    /**
13442     * Check if the external storage media is available. This is true if there
13443     * is a mounted external storage medium or if the external storage is
13444     * emulated.
13445     */
13446    private boolean isExternalMediaAvailable() {
13447        return mMediaMounted || Environment.isExternalStorageEmulated();
13448    }
13449
13450    @Override
13451    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13452        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13453            return null;
13454        }
13455        if (!isExternalMediaAvailable()) {
13456                // If the external storage is no longer mounted at this point,
13457                // the caller may not have been able to delete all of this
13458                // packages files and can not delete any more.  Bail.
13459            return null;
13460        }
13461        synchronized (mPackages) {
13462            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13463            if (lastPackage != null) {
13464                pkgs.remove(lastPackage);
13465            }
13466            if (pkgs.size() > 0) {
13467                return pkgs.get(0);
13468            }
13469        }
13470        return null;
13471    }
13472
13473    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13474        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13475                userId, andCode ? 1 : 0, packageName);
13476        if (mSystemReady) {
13477            msg.sendToTarget();
13478        } else {
13479            if (mPostSystemReadyMessages == null) {
13480                mPostSystemReadyMessages = new ArrayList<>();
13481            }
13482            mPostSystemReadyMessages.add(msg);
13483        }
13484    }
13485
13486    void startCleaningPackages() {
13487        // reader
13488        if (!isExternalMediaAvailable()) {
13489            return;
13490        }
13491        synchronized (mPackages) {
13492            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13493                return;
13494            }
13495        }
13496        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13497        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13498        IActivityManager am = ActivityManager.getService();
13499        if (am != null) {
13500            int dcsUid = -1;
13501            synchronized (mPackages) {
13502                if (!mDefaultContainerWhitelisted) {
13503                    mDefaultContainerWhitelisted = true;
13504                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13505                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13506                }
13507            }
13508            try {
13509                if (dcsUid > 0) {
13510                    am.backgroundWhitelistUid(dcsUid);
13511                }
13512                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13513                        UserHandle.USER_SYSTEM);
13514            } catch (RemoteException e) {
13515            }
13516        }
13517    }
13518
13519    /**
13520     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13521     * it is acting on behalf on an enterprise or the user).
13522     *
13523     * Note that the ordering of the conditionals in this method is important. The checks we perform
13524     * are as follows, in this order:
13525     *
13526     * 1) If the install is being performed by a system app, we can trust the app to have set the
13527     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13528     *    what it is.
13529     * 2) If the install is being performed by a device or profile owner app, the install reason
13530     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13531     *    set the install reason correctly. If the app targets an older SDK version where install
13532     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13533     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13534     * 3) In all other cases, the install is being performed by a regular app that is neither part
13535     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13536     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13537     *    set to enterprise policy and if so, change it to unknown instead.
13538     */
13539    private int fixUpInstallReason(String installerPackageName, int installerUid,
13540            int installReason) {
13541        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13542                == PERMISSION_GRANTED) {
13543            // If the install is being performed by a system app, we trust that app to have set the
13544            // install reason correctly.
13545            return installReason;
13546        }
13547
13548        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13549            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13550        if (dpm != null) {
13551            ComponentName owner = null;
13552            try {
13553                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13554                if (owner == null) {
13555                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13556                }
13557            } catch (RemoteException e) {
13558            }
13559            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13560                // If the install is being performed by a device or profile owner, the install
13561                // reason should be enterprise policy.
13562                return PackageManager.INSTALL_REASON_POLICY;
13563            }
13564        }
13565
13566        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13567            // If the install is being performed by a regular app (i.e. neither system app nor
13568            // device or profile owner), we have no reason to believe that the app is acting on
13569            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13570            // change it to unknown instead.
13571            return PackageManager.INSTALL_REASON_UNKNOWN;
13572        }
13573
13574        // If the install is being performed by a regular app and the install reason was set to any
13575        // value but enterprise policy, leave the install reason unchanged.
13576        return installReason;
13577    }
13578
13579    void installStage(String packageName, File stagedDir,
13580            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13581            String installerPackageName, int installerUid, UserHandle user,
13582            PackageParser.SigningDetails signingDetails) {
13583        if (DEBUG_EPHEMERAL) {
13584            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13585                Slog.d(TAG, "Ephemeral install of " + packageName);
13586            }
13587        }
13588        final VerificationInfo verificationInfo = new VerificationInfo(
13589                sessionParams.originatingUri, sessionParams.referrerUri,
13590                sessionParams.originatingUid, installerUid);
13591
13592        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13593
13594        final Message msg = mHandler.obtainMessage(INIT_COPY);
13595        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13596                sessionParams.installReason);
13597        final InstallParams params = new InstallParams(origin, null, observer,
13598                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13599                verificationInfo, user, sessionParams.abiOverride,
13600                sessionParams.grantedRuntimePermissions, signingDetails, installReason);
13601        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13602        msg.obj = params;
13603
13604        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13605                System.identityHashCode(msg.obj));
13606        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13607                System.identityHashCode(msg.obj));
13608
13609        mHandler.sendMessage(msg);
13610    }
13611
13612    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13613            int userId) {
13614        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13615        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13616        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13617        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13618        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13619                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13620
13621        // Send a session commit broadcast
13622        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13623        info.installReason = pkgSetting.getInstallReason(userId);
13624        info.appPackageName = packageName;
13625        sendSessionCommitBroadcast(info, userId);
13626    }
13627
13628    @Override
13629    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13630            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13631        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13632            return;
13633        }
13634        Bundle extras = new Bundle(1);
13635        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13636        final int uid = UserHandle.getUid(
13637                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13638        extras.putInt(Intent.EXTRA_UID, uid);
13639
13640        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13641                packageName, extras, 0, null, null, userIds, instantUserIds);
13642        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13643            mHandler.post(() -> {
13644                        for (int userId : userIds) {
13645                            sendBootCompletedBroadcastToSystemApp(
13646                                    packageName, includeStopped, userId);
13647                        }
13648                    }
13649            );
13650        }
13651    }
13652
13653    /**
13654     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13655     * automatically without needing an explicit launch.
13656     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13657     */
13658    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13659            int userId) {
13660        // If user is not running, the app didn't miss any broadcast
13661        if (!mUserManagerInternal.isUserRunning(userId)) {
13662            return;
13663        }
13664        final IActivityManager am = ActivityManager.getService();
13665        try {
13666            // Deliver LOCKED_BOOT_COMPLETED first
13667            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13668                    .setPackage(packageName);
13669            if (includeStopped) {
13670                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13671            }
13672            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13673            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13674                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13675
13676            // Deliver BOOT_COMPLETED only if user is unlocked
13677            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13678                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13679                if (includeStopped) {
13680                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13681                }
13682                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13683                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13684            }
13685        } catch (RemoteException e) {
13686            throw e.rethrowFromSystemServer();
13687        }
13688    }
13689
13690    @Override
13691    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13692            int userId) {
13693        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13694        PackageSetting pkgSetting;
13695        final int callingUid = Binder.getCallingUid();
13696        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13697                true /* requireFullPermission */, true /* checkShell */,
13698                "setApplicationHiddenSetting for user " + userId);
13699
13700        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13701            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13702            return false;
13703        }
13704
13705        long callingId = Binder.clearCallingIdentity();
13706        try {
13707            boolean sendAdded = false;
13708            boolean sendRemoved = false;
13709            // writer
13710            synchronized (mPackages) {
13711                pkgSetting = mSettings.mPackages.get(packageName);
13712                if (pkgSetting == null) {
13713                    return false;
13714                }
13715                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13716                    return false;
13717                }
13718                // Do not allow "android" is being disabled
13719                if ("android".equals(packageName)) {
13720                    Slog.w(TAG, "Cannot hide package: android");
13721                    return false;
13722                }
13723                // Cannot hide static shared libs as they are considered
13724                // a part of the using app (emulating static linking). Also
13725                // static libs are installed always on internal storage.
13726                PackageParser.Package pkg = mPackages.get(packageName);
13727                if (pkg != null && pkg.staticSharedLibName != null) {
13728                    Slog.w(TAG, "Cannot hide package: " + packageName
13729                            + " providing static shared library: "
13730                            + pkg.staticSharedLibName);
13731                    return false;
13732                }
13733                // Only allow protected packages to hide themselves.
13734                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13735                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13736                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13737                    return false;
13738                }
13739
13740                if (pkgSetting.getHidden(userId) != hidden) {
13741                    pkgSetting.setHidden(hidden, userId);
13742                    mSettings.writePackageRestrictionsLPr(userId);
13743                    if (hidden) {
13744                        sendRemoved = true;
13745                    } else {
13746                        sendAdded = true;
13747                    }
13748                }
13749            }
13750            if (sendAdded) {
13751                sendPackageAddedForUser(packageName, pkgSetting, userId);
13752                return true;
13753            }
13754            if (sendRemoved) {
13755                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13756                        "hiding pkg");
13757                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13758                return true;
13759            }
13760        } finally {
13761            Binder.restoreCallingIdentity(callingId);
13762        }
13763        return false;
13764    }
13765
13766    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13767            int userId) {
13768        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13769        info.removedPackage = packageName;
13770        info.installerPackageName = pkgSetting.installerPackageName;
13771        info.removedUsers = new int[] {userId};
13772        info.broadcastUsers = new int[] {userId};
13773        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13774        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13775    }
13776
13777    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13778        if (pkgList.length > 0) {
13779            Bundle extras = new Bundle(1);
13780            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13781
13782            sendPackageBroadcast(
13783                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13784                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13785                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13786                    new int[] {userId}, null);
13787        }
13788    }
13789
13790    /**
13791     * Returns true if application is not found or there was an error. Otherwise it returns
13792     * the hidden state of the package for the given user.
13793     */
13794    @Override
13795    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13796        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13797        final int callingUid = Binder.getCallingUid();
13798        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13799                true /* requireFullPermission */, false /* checkShell */,
13800                "getApplicationHidden for user " + userId);
13801        PackageSetting ps;
13802        long callingId = Binder.clearCallingIdentity();
13803        try {
13804            // writer
13805            synchronized (mPackages) {
13806                ps = mSettings.mPackages.get(packageName);
13807                if (ps == null) {
13808                    return true;
13809                }
13810                if (filterAppAccessLPr(ps, callingUid, userId)) {
13811                    return true;
13812                }
13813                return ps.getHidden(userId);
13814            }
13815        } finally {
13816            Binder.restoreCallingIdentity(callingId);
13817        }
13818    }
13819
13820    /**
13821     * @hide
13822     */
13823    @Override
13824    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13825            int installReason) {
13826        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13827                null);
13828        PackageSetting pkgSetting;
13829        final int callingUid = Binder.getCallingUid();
13830        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13831                true /* requireFullPermission */, true /* checkShell */,
13832                "installExistingPackage for user " + userId);
13833        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13834            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13835        }
13836
13837        long callingId = Binder.clearCallingIdentity();
13838        try {
13839            boolean installed = false;
13840            final boolean instantApp =
13841                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13842            final boolean fullApp =
13843                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13844
13845            // writer
13846            synchronized (mPackages) {
13847                pkgSetting = mSettings.mPackages.get(packageName);
13848                if (pkgSetting == null) {
13849                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13850                }
13851                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13852                    // only allow the existing package to be used if it's installed as a full
13853                    // application for at least one user
13854                    boolean installAllowed = false;
13855                    for (int checkUserId : sUserManager.getUserIds()) {
13856                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13857                        if (installAllowed) {
13858                            break;
13859                        }
13860                    }
13861                    if (!installAllowed) {
13862                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13863                    }
13864                }
13865                if (!pkgSetting.getInstalled(userId)) {
13866                    pkgSetting.setInstalled(true, userId);
13867                    pkgSetting.setHidden(false, userId);
13868                    pkgSetting.setInstallReason(installReason, userId);
13869                    mSettings.writePackageRestrictionsLPr(userId);
13870                    mSettings.writeKernelMappingLPr(pkgSetting);
13871                    installed = true;
13872                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13873                    // upgrade app from instant to full; we don't allow app downgrade
13874                    installed = true;
13875                }
13876                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13877            }
13878
13879            if (installed) {
13880                if (pkgSetting.pkg != null) {
13881                    synchronized (mInstallLock) {
13882                        // We don't need to freeze for a brand new install
13883                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13884                    }
13885                }
13886                sendPackageAddedForUser(packageName, pkgSetting, userId);
13887                synchronized (mPackages) {
13888                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13889                }
13890            }
13891        } finally {
13892            Binder.restoreCallingIdentity(callingId);
13893        }
13894
13895        return PackageManager.INSTALL_SUCCEEDED;
13896    }
13897
13898    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13899            boolean instantApp, boolean fullApp) {
13900        // no state specified; do nothing
13901        if (!instantApp && !fullApp) {
13902            return;
13903        }
13904        if (userId != UserHandle.USER_ALL) {
13905            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13906                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13907            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13908                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13909            }
13910        } else {
13911            for (int currentUserId : sUserManager.getUserIds()) {
13912                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13913                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13914                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13915                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13916                }
13917            }
13918        }
13919    }
13920
13921    boolean isUserRestricted(int userId, String restrictionKey) {
13922        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13923        if (restrictions.getBoolean(restrictionKey, false)) {
13924            Log.w(TAG, "User is restricted: " + restrictionKey);
13925            return true;
13926        }
13927        return false;
13928    }
13929
13930    @Override
13931    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13932            int userId) {
13933        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13934        final int callingUid = Binder.getCallingUid();
13935        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13936                true /* requireFullPermission */, true /* checkShell */,
13937                "setPackagesSuspended for user " + userId);
13938
13939        if (ArrayUtils.isEmpty(packageNames)) {
13940            return packageNames;
13941        }
13942
13943        // List of package names for whom the suspended state has changed.
13944        List<String> changedPackages = new ArrayList<>(packageNames.length);
13945        // List of package names for whom the suspended state is not set as requested in this
13946        // method.
13947        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13948        long callingId = Binder.clearCallingIdentity();
13949        try {
13950            for (int i = 0; i < packageNames.length; i++) {
13951                String packageName = packageNames[i];
13952                boolean changed = false;
13953                final int appId;
13954                synchronized (mPackages) {
13955                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13956                    if (pkgSetting == null
13957                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13958                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13959                                + "\". Skipping suspending/un-suspending.");
13960                        unactionedPackages.add(packageName);
13961                        continue;
13962                    }
13963                    appId = pkgSetting.appId;
13964                    if (pkgSetting.getSuspended(userId) != suspended) {
13965                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13966                            unactionedPackages.add(packageName);
13967                            continue;
13968                        }
13969                        pkgSetting.setSuspended(suspended, userId);
13970                        mSettings.writePackageRestrictionsLPr(userId);
13971                        changed = true;
13972                        changedPackages.add(packageName);
13973                    }
13974                }
13975
13976                if (changed && suspended) {
13977                    killApplication(packageName, UserHandle.getUid(userId, appId),
13978                            "suspending package");
13979                }
13980            }
13981        } finally {
13982            Binder.restoreCallingIdentity(callingId);
13983        }
13984
13985        if (!changedPackages.isEmpty()) {
13986            sendPackagesSuspendedForUser(changedPackages.toArray(
13987                    new String[changedPackages.size()]), userId, suspended);
13988        }
13989
13990        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13991    }
13992
13993    @Override
13994    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13995        final int callingUid = Binder.getCallingUid();
13996        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13997                true /* requireFullPermission */, false /* checkShell */,
13998                "isPackageSuspendedForUser for user " + userId);
13999        synchronized (mPackages) {
14000            final PackageSetting ps = mSettings.mPackages.get(packageName);
14001            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14002                throw new IllegalArgumentException("Unknown target package: " + packageName);
14003            }
14004            return ps.getSuspended(userId);
14005        }
14006    }
14007
14008    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14009        if (isPackageDeviceAdmin(packageName, userId)) {
14010            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14011                    + "\": has an active device admin");
14012            return false;
14013        }
14014
14015        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14016        if (packageName.equals(activeLauncherPackageName)) {
14017            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14018                    + "\": contains the active launcher");
14019            return false;
14020        }
14021
14022        if (packageName.equals(mRequiredInstallerPackage)) {
14023            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14024                    + "\": required for package installation");
14025            return false;
14026        }
14027
14028        if (packageName.equals(mRequiredUninstallerPackage)) {
14029            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14030                    + "\": required for package uninstallation");
14031            return false;
14032        }
14033
14034        if (packageName.equals(mRequiredVerifierPackage)) {
14035            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14036                    + "\": required for package verification");
14037            return false;
14038        }
14039
14040        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14041            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14042                    + "\": is the default dialer");
14043            return false;
14044        }
14045
14046        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14047            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14048                    + "\": protected package");
14049            return false;
14050        }
14051
14052        // Cannot suspend static shared libs as they are considered
14053        // a part of the using app (emulating static linking). Also
14054        // static libs are installed always on internal storage.
14055        PackageParser.Package pkg = mPackages.get(packageName);
14056        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14057            Slog.w(TAG, "Cannot suspend package: " + packageName
14058                    + " providing static shared library: "
14059                    + pkg.staticSharedLibName);
14060            return false;
14061        }
14062
14063        return true;
14064    }
14065
14066    private String getActiveLauncherPackageName(int userId) {
14067        Intent intent = new Intent(Intent.ACTION_MAIN);
14068        intent.addCategory(Intent.CATEGORY_HOME);
14069        ResolveInfo resolveInfo = resolveIntent(
14070                intent,
14071                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14072                PackageManager.MATCH_DEFAULT_ONLY,
14073                userId);
14074
14075        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14076    }
14077
14078    private String getDefaultDialerPackageName(int userId) {
14079        synchronized (mPackages) {
14080            return mSettings.getDefaultDialerPackageNameLPw(userId);
14081        }
14082    }
14083
14084    @Override
14085    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14086        mContext.enforceCallingOrSelfPermission(
14087                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14088                "Only package verification agents can verify applications");
14089
14090        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14091        final PackageVerificationResponse response = new PackageVerificationResponse(
14092                verificationCode, Binder.getCallingUid());
14093        msg.arg1 = id;
14094        msg.obj = response;
14095        mHandler.sendMessage(msg);
14096    }
14097
14098    @Override
14099    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14100            long millisecondsToDelay) {
14101        mContext.enforceCallingOrSelfPermission(
14102                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14103                "Only package verification agents can extend verification timeouts");
14104
14105        final PackageVerificationState state = mPendingVerification.get(id);
14106        final PackageVerificationResponse response = new PackageVerificationResponse(
14107                verificationCodeAtTimeout, Binder.getCallingUid());
14108
14109        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14110            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14111        }
14112        if (millisecondsToDelay < 0) {
14113            millisecondsToDelay = 0;
14114        }
14115        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14116                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14117            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14118        }
14119
14120        if ((state != null) && !state.timeoutExtended()) {
14121            state.extendTimeout();
14122
14123            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14124            msg.arg1 = id;
14125            msg.obj = response;
14126            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14127        }
14128    }
14129
14130    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14131            int verificationCode, UserHandle user) {
14132        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14133        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14134        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14135        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14136        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14137
14138        mContext.sendBroadcastAsUser(intent, user,
14139                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14140    }
14141
14142    private ComponentName matchComponentForVerifier(String packageName,
14143            List<ResolveInfo> receivers) {
14144        ActivityInfo targetReceiver = null;
14145
14146        final int NR = receivers.size();
14147        for (int i = 0; i < NR; i++) {
14148            final ResolveInfo info = receivers.get(i);
14149            if (info.activityInfo == null) {
14150                continue;
14151            }
14152
14153            if (packageName.equals(info.activityInfo.packageName)) {
14154                targetReceiver = info.activityInfo;
14155                break;
14156            }
14157        }
14158
14159        if (targetReceiver == null) {
14160            return null;
14161        }
14162
14163        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14164    }
14165
14166    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14167            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14168        if (pkgInfo.verifiers.length == 0) {
14169            return null;
14170        }
14171
14172        final int N = pkgInfo.verifiers.length;
14173        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14174        for (int i = 0; i < N; i++) {
14175            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14176
14177            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14178                    receivers);
14179            if (comp == null) {
14180                continue;
14181            }
14182
14183            final int verifierUid = getUidForVerifier(verifierInfo);
14184            if (verifierUid == -1) {
14185                continue;
14186            }
14187
14188            if (DEBUG_VERIFY) {
14189                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14190                        + " with the correct signature");
14191            }
14192            sufficientVerifiers.add(comp);
14193            verificationState.addSufficientVerifier(verifierUid);
14194        }
14195
14196        return sufficientVerifiers;
14197    }
14198
14199    private int getUidForVerifier(VerifierInfo verifierInfo) {
14200        synchronized (mPackages) {
14201            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14202            if (pkg == null) {
14203                return -1;
14204            } else if (pkg.mSigningDetails.signatures.length != 1) {
14205                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14206                        + " has more than one signature; ignoring");
14207                return -1;
14208            }
14209
14210            /*
14211             * If the public key of the package's signature does not match
14212             * our expected public key, then this is a different package and
14213             * we should skip.
14214             */
14215
14216            final byte[] expectedPublicKey;
14217            try {
14218                final Signature verifierSig = pkg.mSigningDetails.signatures[0];
14219                final PublicKey publicKey = verifierSig.getPublicKey();
14220                expectedPublicKey = publicKey.getEncoded();
14221            } catch (CertificateException e) {
14222                return -1;
14223            }
14224
14225            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14226
14227            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14228                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14229                        + " does not have the expected public key; ignoring");
14230                return -1;
14231            }
14232
14233            return pkg.applicationInfo.uid;
14234        }
14235    }
14236
14237    @Override
14238    public void finishPackageInstall(int token, boolean didLaunch) {
14239        enforceSystemOrRoot("Only the system is allowed to finish installs");
14240
14241        if (DEBUG_INSTALL) {
14242            Slog.v(TAG, "BM finishing package install for " + token);
14243        }
14244        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14245
14246        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14247        mHandler.sendMessage(msg);
14248    }
14249
14250    /**
14251     * Get the verification agent timeout.  Used for both the APK verifier and the
14252     * intent filter verifier.
14253     *
14254     * @return verification timeout in milliseconds
14255     */
14256    private long getVerificationTimeout() {
14257        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14258                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14259                DEFAULT_VERIFICATION_TIMEOUT);
14260    }
14261
14262    /**
14263     * Get the default verification agent response code.
14264     *
14265     * @return default verification response code
14266     */
14267    private int getDefaultVerificationResponse(UserHandle user) {
14268        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14269            return PackageManager.VERIFICATION_REJECT;
14270        }
14271        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14272                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14273                DEFAULT_VERIFICATION_RESPONSE);
14274    }
14275
14276    /**
14277     * Check whether or not package verification has been enabled.
14278     *
14279     * @return true if verification should be performed
14280     */
14281    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14282        if (!DEFAULT_VERIFY_ENABLE) {
14283            return false;
14284        }
14285
14286        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14287
14288        // Check if installing from ADB
14289        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14290            // Do not run verification in a test harness environment
14291            if (ActivityManager.isRunningInTestHarness()) {
14292                return false;
14293            }
14294            if (ensureVerifyAppsEnabled) {
14295                return true;
14296            }
14297            // Check if the developer does not want package verification for ADB installs
14298            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14299                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14300                return false;
14301            }
14302        } else {
14303            // only when not installed from ADB, skip verification for instant apps when
14304            // the installer and verifier are the same.
14305            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14306                if (mInstantAppInstallerActivity != null
14307                        && mInstantAppInstallerActivity.packageName.equals(
14308                                mRequiredVerifierPackage)) {
14309                    try {
14310                        mContext.getSystemService(AppOpsManager.class)
14311                                .checkPackage(installerUid, mRequiredVerifierPackage);
14312                        if (DEBUG_VERIFY) {
14313                            Slog.i(TAG, "disable verification for instant app");
14314                        }
14315                        return false;
14316                    } catch (SecurityException ignore) { }
14317                }
14318            }
14319        }
14320
14321        if (ensureVerifyAppsEnabled) {
14322            return true;
14323        }
14324
14325        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14326                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14327    }
14328
14329    @Override
14330    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14331            throws RemoteException {
14332        mContext.enforceCallingOrSelfPermission(
14333                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14334                "Only intentfilter verification agents can verify applications");
14335
14336        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14337        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14338                Binder.getCallingUid(), verificationCode, failedDomains);
14339        msg.arg1 = id;
14340        msg.obj = response;
14341        mHandler.sendMessage(msg);
14342    }
14343
14344    @Override
14345    public int getIntentVerificationStatus(String packageName, int userId) {
14346        final int callingUid = Binder.getCallingUid();
14347        if (UserHandle.getUserId(callingUid) != userId) {
14348            mContext.enforceCallingOrSelfPermission(
14349                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14350                    "getIntentVerificationStatus" + userId);
14351        }
14352        if (getInstantAppPackageName(callingUid) != null) {
14353            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14354        }
14355        synchronized (mPackages) {
14356            final PackageSetting ps = mSettings.mPackages.get(packageName);
14357            if (ps == null
14358                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14359                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14360            }
14361            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14362        }
14363    }
14364
14365    @Override
14366    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14367        mContext.enforceCallingOrSelfPermission(
14368                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14369
14370        boolean result = false;
14371        synchronized (mPackages) {
14372            final PackageSetting ps = mSettings.mPackages.get(packageName);
14373            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14374                return false;
14375            }
14376            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14377        }
14378        if (result) {
14379            scheduleWritePackageRestrictionsLocked(userId);
14380        }
14381        return result;
14382    }
14383
14384    @Override
14385    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14386            String packageName) {
14387        final int callingUid = Binder.getCallingUid();
14388        if (getInstantAppPackageName(callingUid) != null) {
14389            return ParceledListSlice.emptyList();
14390        }
14391        synchronized (mPackages) {
14392            final PackageSetting ps = mSettings.mPackages.get(packageName);
14393            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14394                return ParceledListSlice.emptyList();
14395            }
14396            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14397        }
14398    }
14399
14400    @Override
14401    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14402        if (TextUtils.isEmpty(packageName)) {
14403            return ParceledListSlice.emptyList();
14404        }
14405        final int callingUid = Binder.getCallingUid();
14406        final int callingUserId = UserHandle.getUserId(callingUid);
14407        synchronized (mPackages) {
14408            PackageParser.Package pkg = mPackages.get(packageName);
14409            if (pkg == null || pkg.activities == null) {
14410                return ParceledListSlice.emptyList();
14411            }
14412            if (pkg.mExtras == null) {
14413                return ParceledListSlice.emptyList();
14414            }
14415            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14416            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14417                return ParceledListSlice.emptyList();
14418            }
14419            final int count = pkg.activities.size();
14420            ArrayList<IntentFilter> result = new ArrayList<>();
14421            for (int n=0; n<count; n++) {
14422                PackageParser.Activity activity = pkg.activities.get(n);
14423                if (activity.intents != null && activity.intents.size() > 0) {
14424                    result.addAll(activity.intents);
14425                }
14426            }
14427            return new ParceledListSlice<>(result);
14428        }
14429    }
14430
14431    @Override
14432    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14433        mContext.enforceCallingOrSelfPermission(
14434                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14435        if (UserHandle.getCallingUserId() != userId) {
14436            mContext.enforceCallingOrSelfPermission(
14437                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14438        }
14439
14440        synchronized (mPackages) {
14441            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14442            if (packageName != null) {
14443                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14444                        packageName, userId);
14445            }
14446            return result;
14447        }
14448    }
14449
14450    @Override
14451    public String getDefaultBrowserPackageName(int userId) {
14452        if (UserHandle.getCallingUserId() != userId) {
14453            mContext.enforceCallingOrSelfPermission(
14454                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14455        }
14456        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14457            return null;
14458        }
14459        synchronized (mPackages) {
14460            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14461        }
14462    }
14463
14464    /**
14465     * Get the "allow unknown sources" setting.
14466     *
14467     * @return the current "allow unknown sources" setting
14468     */
14469    private int getUnknownSourcesSettings() {
14470        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14471                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14472                -1);
14473    }
14474
14475    @Override
14476    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14477        final int callingUid = Binder.getCallingUid();
14478        if (getInstantAppPackageName(callingUid) != null) {
14479            return;
14480        }
14481        // writer
14482        synchronized (mPackages) {
14483            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14484            if (targetPackageSetting == null
14485                    || filterAppAccessLPr(
14486                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14487                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14488            }
14489
14490            PackageSetting installerPackageSetting;
14491            if (installerPackageName != null) {
14492                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14493                if (installerPackageSetting == null) {
14494                    throw new IllegalArgumentException("Unknown installer package: "
14495                            + installerPackageName);
14496                }
14497            } else {
14498                installerPackageSetting = null;
14499            }
14500
14501            Signature[] callerSignature;
14502            Object obj = mSettings.getUserIdLPr(callingUid);
14503            if (obj != null) {
14504                if (obj instanceof SharedUserSetting) {
14505                    callerSignature =
14506                            ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
14507                } else if (obj instanceof PackageSetting) {
14508                    callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
14509                } else {
14510                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14511                }
14512            } else {
14513                throw new SecurityException("Unknown calling UID: " + callingUid);
14514            }
14515
14516            // Verify: can't set installerPackageName to a package that is
14517            // not signed with the same cert as the caller.
14518            if (installerPackageSetting != null) {
14519                if (compareSignatures(callerSignature,
14520                        installerPackageSetting.signatures.mSigningDetails.signatures)
14521                        != PackageManager.SIGNATURE_MATCH) {
14522                    throw new SecurityException(
14523                            "Caller does not have same cert as new installer package "
14524                            + installerPackageName);
14525                }
14526            }
14527
14528            // Verify: if target already has an installer package, it must
14529            // be signed with the same cert as the caller.
14530            if (targetPackageSetting.installerPackageName != null) {
14531                PackageSetting setting = mSettings.mPackages.get(
14532                        targetPackageSetting.installerPackageName);
14533                // If the currently set package isn't valid, then it's always
14534                // okay to change it.
14535                if (setting != null) {
14536                    if (compareSignatures(callerSignature,
14537                            setting.signatures.mSigningDetails.signatures)
14538                            != PackageManager.SIGNATURE_MATCH) {
14539                        throw new SecurityException(
14540                                "Caller does not have same cert as old installer package "
14541                                + targetPackageSetting.installerPackageName);
14542                    }
14543                }
14544            }
14545
14546            // Okay!
14547            targetPackageSetting.installerPackageName = installerPackageName;
14548            if (installerPackageName != null) {
14549                mSettings.mInstallerPackages.add(installerPackageName);
14550            }
14551            scheduleWriteSettingsLocked();
14552        }
14553    }
14554
14555    @Override
14556    public void setApplicationCategoryHint(String packageName, int categoryHint,
14557            String callerPackageName) {
14558        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14559            throw new SecurityException("Instant applications don't have access to this method");
14560        }
14561        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14562                callerPackageName);
14563        synchronized (mPackages) {
14564            PackageSetting ps = mSettings.mPackages.get(packageName);
14565            if (ps == null) {
14566                throw new IllegalArgumentException("Unknown target package " + packageName);
14567            }
14568            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14569                throw new IllegalArgumentException("Unknown target package " + packageName);
14570            }
14571            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14572                throw new IllegalArgumentException("Calling package " + callerPackageName
14573                        + " is not installer for " + packageName);
14574            }
14575
14576            if (ps.categoryHint != categoryHint) {
14577                ps.categoryHint = categoryHint;
14578                scheduleWriteSettingsLocked();
14579            }
14580        }
14581    }
14582
14583    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14584        // Queue up an async operation since the package installation may take a little while.
14585        mHandler.post(new Runnable() {
14586            public void run() {
14587                mHandler.removeCallbacks(this);
14588                 // Result object to be returned
14589                PackageInstalledInfo res = new PackageInstalledInfo();
14590                res.setReturnCode(currentStatus);
14591                res.uid = -1;
14592                res.pkg = null;
14593                res.removedInfo = null;
14594                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14595                    args.doPreInstall(res.returnCode);
14596                    synchronized (mInstallLock) {
14597                        installPackageTracedLI(args, res);
14598                    }
14599                    args.doPostInstall(res.returnCode, res.uid);
14600                }
14601
14602                // A restore should be performed at this point if (a) the install
14603                // succeeded, (b) the operation is not an update, and (c) the new
14604                // package has not opted out of backup participation.
14605                final boolean update = res.removedInfo != null
14606                        && res.removedInfo.removedPackage != null;
14607                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14608                boolean doRestore = !update
14609                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14610
14611                // Set up the post-install work request bookkeeping.  This will be used
14612                // and cleaned up by the post-install event handling regardless of whether
14613                // there's a restore pass performed.  Token values are >= 1.
14614                int token;
14615                if (mNextInstallToken < 0) mNextInstallToken = 1;
14616                token = mNextInstallToken++;
14617
14618                PostInstallData data = new PostInstallData(args, res);
14619                mRunningInstalls.put(token, data);
14620                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14621
14622                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14623                    // Pass responsibility to the Backup Manager.  It will perform a
14624                    // restore if appropriate, then pass responsibility back to the
14625                    // Package Manager to run the post-install observer callbacks
14626                    // and broadcasts.
14627                    IBackupManager bm = IBackupManager.Stub.asInterface(
14628                            ServiceManager.getService(Context.BACKUP_SERVICE));
14629                    if (bm != null) {
14630                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14631                                + " to BM for possible restore");
14632                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14633                        try {
14634                            // TODO: http://b/22388012
14635                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14636                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14637                            } else {
14638                                doRestore = false;
14639                            }
14640                        } catch (RemoteException e) {
14641                            // can't happen; the backup manager is local
14642                        } catch (Exception e) {
14643                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14644                            doRestore = false;
14645                        }
14646                    } else {
14647                        Slog.e(TAG, "Backup Manager not found!");
14648                        doRestore = false;
14649                    }
14650                }
14651
14652                if (!doRestore) {
14653                    // No restore possible, or the Backup Manager was mysteriously not
14654                    // available -- just fire the post-install work request directly.
14655                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14656
14657                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14658
14659                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14660                    mHandler.sendMessage(msg);
14661                }
14662            }
14663        });
14664    }
14665
14666    /**
14667     * Callback from PackageSettings whenever an app is first transitioned out of the
14668     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14669     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14670     * here whether the app is the target of an ongoing install, and only send the
14671     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14672     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14673     * handling.
14674     */
14675    void notifyFirstLaunch(final String packageName, final String installerPackage,
14676            final int userId) {
14677        // Serialize this with the rest of the install-process message chain.  In the
14678        // restore-at-install case, this Runnable will necessarily run before the
14679        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14680        // are coherent.  In the non-restore case, the app has already completed install
14681        // and been launched through some other means, so it is not in a problematic
14682        // state for observers to see the FIRST_LAUNCH signal.
14683        mHandler.post(new Runnable() {
14684            @Override
14685            public void run() {
14686                for (int i = 0; i < mRunningInstalls.size(); i++) {
14687                    final PostInstallData data = mRunningInstalls.valueAt(i);
14688                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14689                        continue;
14690                    }
14691                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14692                        // right package; but is it for the right user?
14693                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14694                            if (userId == data.res.newUsers[uIndex]) {
14695                                if (DEBUG_BACKUP) {
14696                                    Slog.i(TAG, "Package " + packageName
14697                                            + " being restored so deferring FIRST_LAUNCH");
14698                                }
14699                                return;
14700                            }
14701                        }
14702                    }
14703                }
14704                // didn't find it, so not being restored
14705                if (DEBUG_BACKUP) {
14706                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14707                }
14708                final boolean isInstantApp = isInstantApp(packageName, userId);
14709                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14710                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14711                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14712            }
14713        });
14714    }
14715
14716    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14717            int[] userIds, int[] instantUserIds) {
14718        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14719                installerPkg, null, userIds, instantUserIds);
14720    }
14721
14722    private abstract class HandlerParams {
14723        private static final int MAX_RETRIES = 4;
14724
14725        /**
14726         * Number of times startCopy() has been attempted and had a non-fatal
14727         * error.
14728         */
14729        private int mRetries = 0;
14730
14731        /** User handle for the user requesting the information or installation. */
14732        private final UserHandle mUser;
14733        String traceMethod;
14734        int traceCookie;
14735
14736        HandlerParams(UserHandle user) {
14737            mUser = user;
14738        }
14739
14740        UserHandle getUser() {
14741            return mUser;
14742        }
14743
14744        HandlerParams setTraceMethod(String traceMethod) {
14745            this.traceMethod = traceMethod;
14746            return this;
14747        }
14748
14749        HandlerParams setTraceCookie(int traceCookie) {
14750            this.traceCookie = traceCookie;
14751            return this;
14752        }
14753
14754        final boolean startCopy() {
14755            boolean res;
14756            try {
14757                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14758
14759                if (++mRetries > MAX_RETRIES) {
14760                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14761                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14762                    handleServiceError();
14763                    return false;
14764                } else {
14765                    handleStartCopy();
14766                    res = true;
14767                }
14768            } catch (RemoteException e) {
14769                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14770                mHandler.sendEmptyMessage(MCS_RECONNECT);
14771                res = false;
14772            }
14773            handleReturnCode();
14774            return res;
14775        }
14776
14777        final void serviceError() {
14778            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14779            handleServiceError();
14780            handleReturnCode();
14781        }
14782
14783        abstract void handleStartCopy() throws RemoteException;
14784        abstract void handleServiceError();
14785        abstract void handleReturnCode();
14786    }
14787
14788    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14789        for (File path : paths) {
14790            try {
14791                mcs.clearDirectory(path.getAbsolutePath());
14792            } catch (RemoteException e) {
14793            }
14794        }
14795    }
14796
14797    static class OriginInfo {
14798        /**
14799         * Location where install is coming from, before it has been
14800         * copied/renamed into place. This could be a single monolithic APK
14801         * file, or a cluster directory. This location may be untrusted.
14802         */
14803        final File file;
14804
14805        /**
14806         * Flag indicating that {@link #file} or {@link #cid} has already been
14807         * staged, meaning downstream users don't need to defensively copy the
14808         * contents.
14809         */
14810        final boolean staged;
14811
14812        /**
14813         * Flag indicating that {@link #file} or {@link #cid} is an already
14814         * installed app that is being moved.
14815         */
14816        final boolean existing;
14817
14818        final String resolvedPath;
14819        final File resolvedFile;
14820
14821        static OriginInfo fromNothing() {
14822            return new OriginInfo(null, false, false);
14823        }
14824
14825        static OriginInfo fromUntrustedFile(File file) {
14826            return new OriginInfo(file, false, false);
14827        }
14828
14829        static OriginInfo fromExistingFile(File file) {
14830            return new OriginInfo(file, false, true);
14831        }
14832
14833        static OriginInfo fromStagedFile(File file) {
14834            return new OriginInfo(file, true, false);
14835        }
14836
14837        private OriginInfo(File file, boolean staged, boolean existing) {
14838            this.file = file;
14839            this.staged = staged;
14840            this.existing = existing;
14841
14842            if (file != null) {
14843                resolvedPath = file.getAbsolutePath();
14844                resolvedFile = file;
14845            } else {
14846                resolvedPath = null;
14847                resolvedFile = null;
14848            }
14849        }
14850    }
14851
14852    static class MoveInfo {
14853        final int moveId;
14854        final String fromUuid;
14855        final String toUuid;
14856        final String packageName;
14857        final String dataAppName;
14858        final int appId;
14859        final String seinfo;
14860        final int targetSdkVersion;
14861
14862        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14863                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14864            this.moveId = moveId;
14865            this.fromUuid = fromUuid;
14866            this.toUuid = toUuid;
14867            this.packageName = packageName;
14868            this.dataAppName = dataAppName;
14869            this.appId = appId;
14870            this.seinfo = seinfo;
14871            this.targetSdkVersion = targetSdkVersion;
14872        }
14873    }
14874
14875    static class VerificationInfo {
14876        /** A constant used to indicate that a uid value is not present. */
14877        public static final int NO_UID = -1;
14878
14879        /** URI referencing where the package was downloaded from. */
14880        final Uri originatingUri;
14881
14882        /** HTTP referrer URI associated with the originatingURI. */
14883        final Uri referrer;
14884
14885        /** UID of the application that the install request originated from. */
14886        final int originatingUid;
14887
14888        /** UID of application requesting the install */
14889        final int installerUid;
14890
14891        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14892            this.originatingUri = originatingUri;
14893            this.referrer = referrer;
14894            this.originatingUid = originatingUid;
14895            this.installerUid = installerUid;
14896        }
14897    }
14898
14899    class InstallParams extends HandlerParams {
14900        final OriginInfo origin;
14901        final MoveInfo move;
14902        final IPackageInstallObserver2 observer;
14903        int installFlags;
14904        final String installerPackageName;
14905        final String volumeUuid;
14906        private InstallArgs mArgs;
14907        private int mRet;
14908        final String packageAbiOverride;
14909        final String[] grantedRuntimePermissions;
14910        final VerificationInfo verificationInfo;
14911        final PackageParser.SigningDetails signingDetails;
14912        final int installReason;
14913
14914        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14915                int installFlags, String installerPackageName, String volumeUuid,
14916                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14917                String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
14918            super(user);
14919            this.origin = origin;
14920            this.move = move;
14921            this.observer = observer;
14922            this.installFlags = installFlags;
14923            this.installerPackageName = installerPackageName;
14924            this.volumeUuid = volumeUuid;
14925            this.verificationInfo = verificationInfo;
14926            this.packageAbiOverride = packageAbiOverride;
14927            this.grantedRuntimePermissions = grantedPermissions;
14928            this.signingDetails = signingDetails;
14929            this.installReason = installReason;
14930        }
14931
14932        @Override
14933        public String toString() {
14934            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14935                    + " file=" + origin.file + "}";
14936        }
14937
14938        private int installLocationPolicy(PackageInfoLite pkgLite) {
14939            String packageName = pkgLite.packageName;
14940            int installLocation = pkgLite.installLocation;
14941            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14942            // reader
14943            synchronized (mPackages) {
14944                // Currently installed package which the new package is attempting to replace or
14945                // null if no such package is installed.
14946                PackageParser.Package installedPkg = mPackages.get(packageName);
14947                // Package which currently owns the data which the new package will own if installed.
14948                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14949                // will be null whereas dataOwnerPkg will contain information about the package
14950                // which was uninstalled while keeping its data.
14951                PackageParser.Package dataOwnerPkg = installedPkg;
14952                if (dataOwnerPkg  == null) {
14953                    PackageSetting ps = mSettings.mPackages.get(packageName);
14954                    if (ps != null) {
14955                        dataOwnerPkg = ps.pkg;
14956                    }
14957                }
14958
14959                if (dataOwnerPkg != null) {
14960                    // If installed, the package will get access to data left on the device by its
14961                    // predecessor. As a security measure, this is permited only if this is not a
14962                    // version downgrade or if the predecessor package is marked as debuggable and
14963                    // a downgrade is explicitly requested.
14964                    //
14965                    // On debuggable platform builds, downgrades are permitted even for
14966                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14967                    // not offer security guarantees and thus it's OK to disable some security
14968                    // mechanisms to make debugging/testing easier on those builds. However, even on
14969                    // debuggable builds downgrades of packages are permitted only if requested via
14970                    // installFlags. This is because we aim to keep the behavior of debuggable
14971                    // platform builds as close as possible to the behavior of non-debuggable
14972                    // platform builds.
14973                    final boolean downgradeRequested =
14974                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14975                    final boolean packageDebuggable =
14976                                (dataOwnerPkg.applicationInfo.flags
14977                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14978                    final boolean downgradePermitted =
14979                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14980                    if (!downgradePermitted) {
14981                        try {
14982                            checkDowngrade(dataOwnerPkg, pkgLite);
14983                        } catch (PackageManagerException e) {
14984                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14985                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14986                        }
14987                    }
14988                }
14989
14990                if (installedPkg != null) {
14991                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14992                        // Check for updated system application.
14993                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14994                            if (onSd) {
14995                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14996                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14997                            }
14998                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14999                        } else {
15000                            if (onSd) {
15001                                // Install flag overrides everything.
15002                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15003                            }
15004                            // If current upgrade specifies particular preference
15005                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15006                                // Application explicitly specified internal.
15007                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15008                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15009                                // App explictly prefers external. Let policy decide
15010                            } else {
15011                                // Prefer previous location
15012                                if (isExternal(installedPkg)) {
15013                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15014                                }
15015                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15016                            }
15017                        }
15018                    } else {
15019                        // Invalid install. Return error code
15020                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15021                    }
15022                }
15023            }
15024            // All the special cases have been taken care of.
15025            // Return result based on recommended install location.
15026            if (onSd) {
15027                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15028            }
15029            return pkgLite.recommendedInstallLocation;
15030        }
15031
15032        /*
15033         * Invoke remote method to get package information and install
15034         * location values. Override install location based on default
15035         * policy if needed and then create install arguments based
15036         * on the install location.
15037         */
15038        public void handleStartCopy() throws RemoteException {
15039            int ret = PackageManager.INSTALL_SUCCEEDED;
15040
15041            // If we're already staged, we've firmly committed to an install location
15042            if (origin.staged) {
15043                if (origin.file != null) {
15044                    installFlags |= PackageManager.INSTALL_INTERNAL;
15045                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15046                } else {
15047                    throw new IllegalStateException("Invalid stage location");
15048                }
15049            }
15050
15051            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15052            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15053            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15054            PackageInfoLite pkgLite = null;
15055
15056            if (onInt && onSd) {
15057                // Check if both bits are set.
15058                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15059                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15060            } else if (onSd && ephemeral) {
15061                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15062                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15063            } else {
15064                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15065                        packageAbiOverride);
15066
15067                if (DEBUG_EPHEMERAL && ephemeral) {
15068                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15069                }
15070
15071                /*
15072                 * If we have too little free space, try to free cache
15073                 * before giving up.
15074                 */
15075                if (!origin.staged && pkgLite.recommendedInstallLocation
15076                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15077                    // TODO: focus freeing disk space on the target device
15078                    final StorageManager storage = StorageManager.from(mContext);
15079                    final long lowThreshold = storage.getStorageLowBytes(
15080                            Environment.getDataDirectory());
15081
15082                    final long sizeBytes = mContainerService.calculateInstalledSize(
15083                            origin.resolvedPath, packageAbiOverride);
15084
15085                    try {
15086                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15087                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15088                                installFlags, packageAbiOverride);
15089                    } catch (InstallerException e) {
15090                        Slog.w(TAG, "Failed to free cache", e);
15091                    }
15092
15093                    /*
15094                     * The cache free must have deleted the file we
15095                     * downloaded to install.
15096                     *
15097                     * TODO: fix the "freeCache" call to not delete
15098                     *       the file we care about.
15099                     */
15100                    if (pkgLite.recommendedInstallLocation
15101                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15102                        pkgLite.recommendedInstallLocation
15103                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15104                    }
15105                }
15106            }
15107
15108            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15109                int loc = pkgLite.recommendedInstallLocation;
15110                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15111                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15112                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15113                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15114                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15115                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15116                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15117                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15118                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15119                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15120                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15121                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15122                } else {
15123                    // Override with defaults if needed.
15124                    loc = installLocationPolicy(pkgLite);
15125                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15126                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15127                    } else if (!onSd && !onInt) {
15128                        // Override install location with flags
15129                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15130                            // Set the flag to install on external media.
15131                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15132                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15133                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15134                            if (DEBUG_EPHEMERAL) {
15135                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15136                            }
15137                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15138                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15139                                    |PackageManager.INSTALL_INTERNAL);
15140                        } else {
15141                            // Make sure the flag for installing on external
15142                            // media is unset
15143                            installFlags |= PackageManager.INSTALL_INTERNAL;
15144                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15145                        }
15146                    }
15147                }
15148            }
15149
15150            final InstallArgs args = createInstallArgs(this);
15151            mArgs = args;
15152
15153            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15154                // TODO: http://b/22976637
15155                // Apps installed for "all" users use the device owner to verify the app
15156                UserHandle verifierUser = getUser();
15157                if (verifierUser == UserHandle.ALL) {
15158                    verifierUser = UserHandle.SYSTEM;
15159                }
15160
15161                /*
15162                 * Determine if we have any installed package verifiers. If we
15163                 * do, then we'll defer to them to verify the packages.
15164                 */
15165                final int requiredUid = mRequiredVerifierPackage == null ? -1
15166                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15167                                verifierUser.getIdentifier());
15168                final int installerUid =
15169                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15170                if (!origin.existing && requiredUid != -1
15171                        && isVerificationEnabled(
15172                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15173                    final Intent verification = new Intent(
15174                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15175                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15176                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15177                            PACKAGE_MIME_TYPE);
15178                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15179
15180                    // Query all live verifiers based on current user state
15181                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15182                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15183                            false /*allowDynamicSplits*/);
15184
15185                    if (DEBUG_VERIFY) {
15186                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15187                                + verification.toString() + " with " + pkgLite.verifiers.length
15188                                + " optional verifiers");
15189                    }
15190
15191                    final int verificationId = mPendingVerificationToken++;
15192
15193                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15194
15195                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15196                            installerPackageName);
15197
15198                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15199                            installFlags);
15200
15201                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15202                            pkgLite.packageName);
15203
15204                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15205                            pkgLite.versionCode);
15206
15207                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
15208                            pkgLite.getLongVersionCode());
15209
15210                    if (verificationInfo != null) {
15211                        if (verificationInfo.originatingUri != null) {
15212                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15213                                    verificationInfo.originatingUri);
15214                        }
15215                        if (verificationInfo.referrer != null) {
15216                            verification.putExtra(Intent.EXTRA_REFERRER,
15217                                    verificationInfo.referrer);
15218                        }
15219                        if (verificationInfo.originatingUid >= 0) {
15220                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15221                                    verificationInfo.originatingUid);
15222                        }
15223                        if (verificationInfo.installerUid >= 0) {
15224                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15225                                    verificationInfo.installerUid);
15226                        }
15227                    }
15228
15229                    final PackageVerificationState verificationState = new PackageVerificationState(
15230                            requiredUid, args);
15231
15232                    mPendingVerification.append(verificationId, verificationState);
15233
15234                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15235                            receivers, verificationState);
15236
15237                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15238                    final long idleDuration = getVerificationTimeout();
15239
15240                    /*
15241                     * If any sufficient verifiers were listed in the package
15242                     * manifest, attempt to ask them.
15243                     */
15244                    if (sufficientVerifiers != null) {
15245                        final int N = sufficientVerifiers.size();
15246                        if (N == 0) {
15247                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15248                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15249                        } else {
15250                            for (int i = 0; i < N; i++) {
15251                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15252                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15253                                        verifierComponent.getPackageName(), idleDuration,
15254                                        verifierUser.getIdentifier(), false, "package verifier");
15255
15256                                final Intent sufficientIntent = new Intent(verification);
15257                                sufficientIntent.setComponent(verifierComponent);
15258                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15259                            }
15260                        }
15261                    }
15262
15263                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15264                            mRequiredVerifierPackage, receivers);
15265                    if (ret == PackageManager.INSTALL_SUCCEEDED
15266                            && mRequiredVerifierPackage != null) {
15267                        Trace.asyncTraceBegin(
15268                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15269                        /*
15270                         * Send the intent to the required verification agent,
15271                         * but only start the verification timeout after the
15272                         * target BroadcastReceivers have run.
15273                         */
15274                        verification.setComponent(requiredVerifierComponent);
15275                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15276                                mRequiredVerifierPackage, idleDuration,
15277                                verifierUser.getIdentifier(), false, "package verifier");
15278                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15279                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15280                                new BroadcastReceiver() {
15281                                    @Override
15282                                    public void onReceive(Context context, Intent intent) {
15283                                        final Message msg = mHandler
15284                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15285                                        msg.arg1 = verificationId;
15286                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15287                                    }
15288                                }, null, 0, null, null);
15289
15290                        /*
15291                         * We don't want the copy to proceed until verification
15292                         * succeeds, so null out this field.
15293                         */
15294                        mArgs = null;
15295                    }
15296                } else {
15297                    /*
15298                     * No package verification is enabled, so immediately start
15299                     * the remote call to initiate copy using temporary file.
15300                     */
15301                    ret = args.copyApk(mContainerService, true);
15302                }
15303            }
15304
15305            mRet = ret;
15306        }
15307
15308        @Override
15309        void handleReturnCode() {
15310            // If mArgs is null, then MCS couldn't be reached. When it
15311            // reconnects, it will try again to install. At that point, this
15312            // will succeed.
15313            if (mArgs != null) {
15314                processPendingInstall(mArgs, mRet);
15315            }
15316        }
15317
15318        @Override
15319        void handleServiceError() {
15320            mArgs = createInstallArgs(this);
15321            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15322        }
15323    }
15324
15325    private InstallArgs createInstallArgs(InstallParams params) {
15326        if (params.move != null) {
15327            return new MoveInstallArgs(params);
15328        } else {
15329            return new FileInstallArgs(params);
15330        }
15331    }
15332
15333    /**
15334     * Create args that describe an existing installed package. Typically used
15335     * when cleaning up old installs, or used as a move source.
15336     */
15337    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15338            String resourcePath, String[] instructionSets) {
15339        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15340    }
15341
15342    static abstract class InstallArgs {
15343        /** @see InstallParams#origin */
15344        final OriginInfo origin;
15345        /** @see InstallParams#move */
15346        final MoveInfo move;
15347
15348        final IPackageInstallObserver2 observer;
15349        // Always refers to PackageManager flags only
15350        final int installFlags;
15351        final String installerPackageName;
15352        final String volumeUuid;
15353        final UserHandle user;
15354        final String abiOverride;
15355        final String[] installGrantPermissions;
15356        /** If non-null, drop an async trace when the install completes */
15357        final String traceMethod;
15358        final int traceCookie;
15359        final PackageParser.SigningDetails signingDetails;
15360        final int installReason;
15361
15362        // The list of instruction sets supported by this app. This is currently
15363        // only used during the rmdex() phase to clean up resources. We can get rid of this
15364        // if we move dex files under the common app path.
15365        /* nullable */ String[] instructionSets;
15366
15367        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15368                int installFlags, String installerPackageName, String volumeUuid,
15369                UserHandle user, String[] instructionSets,
15370                String abiOverride, String[] installGrantPermissions,
15371                String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
15372                int installReason) {
15373            this.origin = origin;
15374            this.move = move;
15375            this.installFlags = installFlags;
15376            this.observer = observer;
15377            this.installerPackageName = installerPackageName;
15378            this.volumeUuid = volumeUuid;
15379            this.user = user;
15380            this.instructionSets = instructionSets;
15381            this.abiOverride = abiOverride;
15382            this.installGrantPermissions = installGrantPermissions;
15383            this.traceMethod = traceMethod;
15384            this.traceCookie = traceCookie;
15385            this.signingDetails = signingDetails;
15386            this.installReason = installReason;
15387        }
15388
15389        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15390        abstract int doPreInstall(int status);
15391
15392        /**
15393         * Rename package into final resting place. All paths on the given
15394         * scanned package should be updated to reflect the rename.
15395         */
15396        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15397        abstract int doPostInstall(int status, int uid);
15398
15399        /** @see PackageSettingBase#codePathString */
15400        abstract String getCodePath();
15401        /** @see PackageSettingBase#resourcePathString */
15402        abstract String getResourcePath();
15403
15404        // Need installer lock especially for dex file removal.
15405        abstract void cleanUpResourcesLI();
15406        abstract boolean doPostDeleteLI(boolean delete);
15407
15408        /**
15409         * Called before the source arguments are copied. This is used mostly
15410         * for MoveParams when it needs to read the source file to put it in the
15411         * destination.
15412         */
15413        int doPreCopy() {
15414            return PackageManager.INSTALL_SUCCEEDED;
15415        }
15416
15417        /**
15418         * Called after the source arguments are copied. This is used mostly for
15419         * MoveParams when it needs to read the source file to put it in the
15420         * destination.
15421         */
15422        int doPostCopy(int uid) {
15423            return PackageManager.INSTALL_SUCCEEDED;
15424        }
15425
15426        protected boolean isFwdLocked() {
15427            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15428        }
15429
15430        protected boolean isExternalAsec() {
15431            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15432        }
15433
15434        protected boolean isEphemeral() {
15435            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15436        }
15437
15438        UserHandle getUser() {
15439            return user;
15440        }
15441    }
15442
15443    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15444        if (!allCodePaths.isEmpty()) {
15445            if (instructionSets == null) {
15446                throw new IllegalStateException("instructionSet == null");
15447            }
15448            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15449            for (String codePath : allCodePaths) {
15450                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15451                    try {
15452                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15453                    } catch (InstallerException ignored) {
15454                    }
15455                }
15456            }
15457        }
15458    }
15459
15460    /**
15461     * Logic to handle installation of non-ASEC applications, including copying
15462     * and renaming logic.
15463     */
15464    class FileInstallArgs extends InstallArgs {
15465        private File codeFile;
15466        private File resourceFile;
15467
15468        // Example topology:
15469        // /data/app/com.example/base.apk
15470        // /data/app/com.example/split_foo.apk
15471        // /data/app/com.example/lib/arm/libfoo.so
15472        // /data/app/com.example/lib/arm64/libfoo.so
15473        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15474
15475        /** New install */
15476        FileInstallArgs(InstallParams params) {
15477            super(params.origin, params.move, params.observer, params.installFlags,
15478                    params.installerPackageName, params.volumeUuid,
15479                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15480                    params.grantedRuntimePermissions,
15481                    params.traceMethod, params.traceCookie, params.signingDetails,
15482                    params.installReason);
15483            if (isFwdLocked()) {
15484                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15485            }
15486        }
15487
15488        /** Existing install */
15489        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15490            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15491                    null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15492                    PackageManager.INSTALL_REASON_UNKNOWN);
15493            this.codeFile = (codePath != null) ? new File(codePath) : null;
15494            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15495        }
15496
15497        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15498            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15499            try {
15500                return doCopyApk(imcs, temp);
15501            } finally {
15502                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15503            }
15504        }
15505
15506        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15507            if (origin.staged) {
15508                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15509                codeFile = origin.file;
15510                resourceFile = origin.file;
15511                return PackageManager.INSTALL_SUCCEEDED;
15512            }
15513
15514            try {
15515                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15516                final File tempDir =
15517                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15518                codeFile = tempDir;
15519                resourceFile = tempDir;
15520            } catch (IOException e) {
15521                Slog.w(TAG, "Failed to create copy file: " + e);
15522                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15523            }
15524
15525            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15526                @Override
15527                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15528                    if (!FileUtils.isValidExtFilename(name)) {
15529                        throw new IllegalArgumentException("Invalid filename: " + name);
15530                    }
15531                    try {
15532                        final File file = new File(codeFile, name);
15533                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15534                                O_RDWR | O_CREAT, 0644);
15535                        Os.chmod(file.getAbsolutePath(), 0644);
15536                        return new ParcelFileDescriptor(fd);
15537                    } catch (ErrnoException e) {
15538                        throw new RemoteException("Failed to open: " + e.getMessage());
15539                    }
15540                }
15541            };
15542
15543            int ret = PackageManager.INSTALL_SUCCEEDED;
15544            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15545            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15546                Slog.e(TAG, "Failed to copy package");
15547                return ret;
15548            }
15549
15550            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15551            NativeLibraryHelper.Handle handle = null;
15552            try {
15553                handle = NativeLibraryHelper.Handle.create(codeFile);
15554                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15555                        abiOverride);
15556            } catch (IOException e) {
15557                Slog.e(TAG, "Copying native libraries failed", e);
15558                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15559            } finally {
15560                IoUtils.closeQuietly(handle);
15561            }
15562
15563            return ret;
15564        }
15565
15566        int doPreInstall(int status) {
15567            if (status != PackageManager.INSTALL_SUCCEEDED) {
15568                cleanUp();
15569            }
15570            return status;
15571        }
15572
15573        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15574            if (status != PackageManager.INSTALL_SUCCEEDED) {
15575                cleanUp();
15576                return false;
15577            }
15578
15579            final File targetDir = codeFile.getParentFile();
15580            final File beforeCodeFile = codeFile;
15581            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15582
15583            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15584            try {
15585                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15586            } catch (ErrnoException e) {
15587                Slog.w(TAG, "Failed to rename", e);
15588                return false;
15589            }
15590
15591            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15592                Slog.w(TAG, "Failed to restorecon");
15593                return false;
15594            }
15595
15596            // Reflect the rename internally
15597            codeFile = afterCodeFile;
15598            resourceFile = afterCodeFile;
15599
15600            // Reflect the rename in scanned details
15601            try {
15602                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15603            } catch (IOException e) {
15604                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15605                return false;
15606            }
15607            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15608                    afterCodeFile, pkg.baseCodePath));
15609            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15610                    afterCodeFile, pkg.splitCodePaths));
15611
15612            // Reflect the rename in app info
15613            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15614            pkg.setApplicationInfoCodePath(pkg.codePath);
15615            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15616            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15617            pkg.setApplicationInfoResourcePath(pkg.codePath);
15618            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15619            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15620
15621            return true;
15622        }
15623
15624        int doPostInstall(int status, int uid) {
15625            if (status != PackageManager.INSTALL_SUCCEEDED) {
15626                cleanUp();
15627            }
15628            return status;
15629        }
15630
15631        @Override
15632        String getCodePath() {
15633            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15634        }
15635
15636        @Override
15637        String getResourcePath() {
15638            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15639        }
15640
15641        private boolean cleanUp() {
15642            if (codeFile == null || !codeFile.exists()) {
15643                return false;
15644            }
15645
15646            removeCodePathLI(codeFile);
15647
15648            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15649                resourceFile.delete();
15650            }
15651
15652            return true;
15653        }
15654
15655        void cleanUpResourcesLI() {
15656            // Try enumerating all code paths before deleting
15657            List<String> allCodePaths = Collections.EMPTY_LIST;
15658            if (codeFile != null && codeFile.exists()) {
15659                try {
15660                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15661                    allCodePaths = pkg.getAllCodePaths();
15662                } catch (PackageParserException e) {
15663                    // Ignored; we tried our best
15664                }
15665            }
15666
15667            cleanUp();
15668            removeDexFiles(allCodePaths, instructionSets);
15669        }
15670
15671        boolean doPostDeleteLI(boolean delete) {
15672            // XXX err, shouldn't we respect the delete flag?
15673            cleanUpResourcesLI();
15674            return true;
15675        }
15676    }
15677
15678    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15679            PackageManagerException {
15680        if (copyRet < 0) {
15681            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15682                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15683                throw new PackageManagerException(copyRet, message);
15684            }
15685        }
15686    }
15687
15688    /**
15689     * Extract the StorageManagerService "container ID" from the full code path of an
15690     * .apk.
15691     */
15692    static String cidFromCodePath(String fullCodePath) {
15693        int eidx = fullCodePath.lastIndexOf("/");
15694        String subStr1 = fullCodePath.substring(0, eidx);
15695        int sidx = subStr1.lastIndexOf("/");
15696        return subStr1.substring(sidx+1, eidx);
15697    }
15698
15699    /**
15700     * Logic to handle movement of existing installed applications.
15701     */
15702    class MoveInstallArgs extends InstallArgs {
15703        private File codeFile;
15704        private File resourceFile;
15705
15706        /** New install */
15707        MoveInstallArgs(InstallParams params) {
15708            super(params.origin, params.move, params.observer, params.installFlags,
15709                    params.installerPackageName, params.volumeUuid,
15710                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15711                    params.grantedRuntimePermissions,
15712                    params.traceMethod, params.traceCookie, params.signingDetails,
15713                    params.installReason);
15714        }
15715
15716        int copyApk(IMediaContainerService imcs, boolean temp) {
15717            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15718                    + move.fromUuid + " to " + move.toUuid);
15719            synchronized (mInstaller) {
15720                try {
15721                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15722                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15723                } catch (InstallerException e) {
15724                    Slog.w(TAG, "Failed to move app", e);
15725                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15726                }
15727            }
15728
15729            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15730            resourceFile = codeFile;
15731            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15732
15733            return PackageManager.INSTALL_SUCCEEDED;
15734        }
15735
15736        int doPreInstall(int status) {
15737            if (status != PackageManager.INSTALL_SUCCEEDED) {
15738                cleanUp(move.toUuid);
15739            }
15740            return status;
15741        }
15742
15743        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15744            if (status != PackageManager.INSTALL_SUCCEEDED) {
15745                cleanUp(move.toUuid);
15746                return false;
15747            }
15748
15749            // Reflect the move in app info
15750            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15751            pkg.setApplicationInfoCodePath(pkg.codePath);
15752            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15753            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15754            pkg.setApplicationInfoResourcePath(pkg.codePath);
15755            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15756            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15757
15758            return true;
15759        }
15760
15761        int doPostInstall(int status, int uid) {
15762            if (status == PackageManager.INSTALL_SUCCEEDED) {
15763                cleanUp(move.fromUuid);
15764            } else {
15765                cleanUp(move.toUuid);
15766            }
15767            return status;
15768        }
15769
15770        @Override
15771        String getCodePath() {
15772            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15773        }
15774
15775        @Override
15776        String getResourcePath() {
15777            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15778        }
15779
15780        private boolean cleanUp(String volumeUuid) {
15781            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15782                    move.dataAppName);
15783            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15784            final int[] userIds = sUserManager.getUserIds();
15785            synchronized (mInstallLock) {
15786                // Clean up both app data and code
15787                // All package moves are frozen until finished
15788                for (int userId : userIds) {
15789                    try {
15790                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15791                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15792                    } catch (InstallerException e) {
15793                        Slog.w(TAG, String.valueOf(e));
15794                    }
15795                }
15796                removeCodePathLI(codeFile);
15797            }
15798            return true;
15799        }
15800
15801        void cleanUpResourcesLI() {
15802            throw new UnsupportedOperationException();
15803        }
15804
15805        boolean doPostDeleteLI(boolean delete) {
15806            throw new UnsupportedOperationException();
15807        }
15808    }
15809
15810    static String getAsecPackageName(String packageCid) {
15811        int idx = packageCid.lastIndexOf("-");
15812        if (idx == -1) {
15813            return packageCid;
15814        }
15815        return packageCid.substring(0, idx);
15816    }
15817
15818    // Utility method used to create code paths based on package name and available index.
15819    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15820        String idxStr = "";
15821        int idx = 1;
15822        // Fall back to default value of idx=1 if prefix is not
15823        // part of oldCodePath
15824        if (oldCodePath != null) {
15825            String subStr = oldCodePath;
15826            // Drop the suffix right away
15827            if (suffix != null && subStr.endsWith(suffix)) {
15828                subStr = subStr.substring(0, subStr.length() - suffix.length());
15829            }
15830            // If oldCodePath already contains prefix find out the
15831            // ending index to either increment or decrement.
15832            int sidx = subStr.lastIndexOf(prefix);
15833            if (sidx != -1) {
15834                subStr = subStr.substring(sidx + prefix.length());
15835                if (subStr != null) {
15836                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15837                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15838                    }
15839                    try {
15840                        idx = Integer.parseInt(subStr);
15841                        if (idx <= 1) {
15842                            idx++;
15843                        } else {
15844                            idx--;
15845                        }
15846                    } catch(NumberFormatException e) {
15847                    }
15848                }
15849            }
15850        }
15851        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15852        return prefix + idxStr;
15853    }
15854
15855    private File getNextCodePath(File targetDir, String packageName) {
15856        File result;
15857        SecureRandom random = new SecureRandom();
15858        byte[] bytes = new byte[16];
15859        do {
15860            random.nextBytes(bytes);
15861            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15862            result = new File(targetDir, packageName + "-" + suffix);
15863        } while (result.exists());
15864        return result;
15865    }
15866
15867    // Utility method that returns the relative package path with respect
15868    // to the installation directory. Like say for /data/data/com.test-1.apk
15869    // string com.test-1 is returned.
15870    static String deriveCodePathName(String codePath) {
15871        if (codePath == null) {
15872            return null;
15873        }
15874        final File codeFile = new File(codePath);
15875        final String name = codeFile.getName();
15876        if (codeFile.isDirectory()) {
15877            return name;
15878        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15879            final int lastDot = name.lastIndexOf('.');
15880            return name.substring(0, lastDot);
15881        } else {
15882            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15883            return null;
15884        }
15885    }
15886
15887    static class PackageInstalledInfo {
15888        String name;
15889        int uid;
15890        // The set of users that originally had this package installed.
15891        int[] origUsers;
15892        // The set of users that now have this package installed.
15893        int[] newUsers;
15894        PackageParser.Package pkg;
15895        int returnCode;
15896        String returnMsg;
15897        String installerPackageName;
15898        PackageRemovedInfo removedInfo;
15899        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15900
15901        public void setError(int code, String msg) {
15902            setReturnCode(code);
15903            setReturnMessage(msg);
15904            Slog.w(TAG, msg);
15905        }
15906
15907        public void setError(String msg, PackageParserException e) {
15908            setReturnCode(e.error);
15909            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15910            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15911            for (int i = 0; i < childCount; i++) {
15912                addedChildPackages.valueAt(i).setError(msg, e);
15913            }
15914            Slog.w(TAG, msg, e);
15915        }
15916
15917        public void setError(String msg, PackageManagerException e) {
15918            returnCode = e.error;
15919            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15920            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15921            for (int i = 0; i < childCount; i++) {
15922                addedChildPackages.valueAt(i).setError(msg, e);
15923            }
15924            Slog.w(TAG, msg, e);
15925        }
15926
15927        public void setReturnCode(int returnCode) {
15928            this.returnCode = returnCode;
15929            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15930            for (int i = 0; i < childCount; i++) {
15931                addedChildPackages.valueAt(i).returnCode = returnCode;
15932            }
15933        }
15934
15935        private void setReturnMessage(String returnMsg) {
15936            this.returnMsg = returnMsg;
15937            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15938            for (int i = 0; i < childCount; i++) {
15939                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15940            }
15941        }
15942
15943        // In some error cases we want to convey more info back to the observer
15944        String origPackage;
15945        String origPermission;
15946    }
15947
15948    /*
15949     * Install a non-existing package.
15950     */
15951    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15952            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15953            String volumeUuid, PackageInstalledInfo res, int installReason) {
15954        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15955
15956        // Remember this for later, in case we need to rollback this install
15957        String pkgName = pkg.packageName;
15958
15959        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15960
15961        synchronized(mPackages) {
15962            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15963            if (renamedPackage != null) {
15964                // A package with the same name is already installed, though
15965                // it has been renamed to an older name.  The package we
15966                // are trying to install should be installed as an update to
15967                // the existing one, but that has not been requested, so bail.
15968                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15969                        + " without first uninstalling package running as "
15970                        + renamedPackage);
15971                return;
15972            }
15973            if (mPackages.containsKey(pkgName)) {
15974                // Don't allow installation over an existing package with the same name.
15975                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15976                        + " without first uninstalling.");
15977                return;
15978            }
15979        }
15980
15981        try {
15982            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
15983                    System.currentTimeMillis(), user);
15984
15985            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15986
15987            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15988                prepareAppDataAfterInstallLIF(newPackage);
15989
15990            } else {
15991                // Remove package from internal structures, but keep around any
15992                // data that might have already existed
15993                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15994                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15995            }
15996        } catch (PackageManagerException e) {
15997            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15998        }
15999
16000        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16001    }
16002
16003    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16004        try (DigestInputStream digestStream =
16005                new DigestInputStream(new FileInputStream(file), digest)) {
16006            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16007        }
16008    }
16009
16010    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16011            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16012            PackageInstalledInfo res, int installReason) {
16013        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16014
16015        final PackageParser.Package oldPackage;
16016        final PackageSetting ps;
16017        final String pkgName = pkg.packageName;
16018        final int[] allUsers;
16019        final int[] installedUsers;
16020
16021        synchronized(mPackages) {
16022            oldPackage = mPackages.get(pkgName);
16023            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16024
16025            // don't allow upgrade to target a release SDK from a pre-release SDK
16026            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16027                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16028            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16029                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16030            if (oldTargetsPreRelease
16031                    && !newTargetsPreRelease
16032                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16033                Slog.w(TAG, "Can't install package targeting released sdk");
16034                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16035                return;
16036            }
16037
16038            ps = mSettings.mPackages.get(pkgName);
16039
16040            // verify signatures are valid
16041            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16042            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
16043                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
16044                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16045                            "New package not signed by keys specified by upgrade-keysets: "
16046                                    + pkgName);
16047                    return;
16048                }
16049            } else {
16050                // default to original signature matching
16051                if (compareSignatures(oldPackage.mSigningDetails.signatures,
16052                        pkg.mSigningDetails.signatures)
16053                        != PackageManager.SIGNATURE_MATCH) {
16054                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16055                            "New package has a different signature: " + pkgName);
16056                    return;
16057                }
16058            }
16059
16060            // don't allow a system upgrade unless the upgrade hash matches
16061            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
16062                byte[] digestBytes = null;
16063                try {
16064                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16065                    updateDigest(digest, new File(pkg.baseCodePath));
16066                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16067                        for (String path : pkg.splitCodePaths) {
16068                            updateDigest(digest, new File(path));
16069                        }
16070                    }
16071                    digestBytes = digest.digest();
16072                } catch (NoSuchAlgorithmException | IOException e) {
16073                    res.setError(INSTALL_FAILED_INVALID_APK,
16074                            "Could not compute hash: " + pkgName);
16075                    return;
16076                }
16077                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16078                    res.setError(INSTALL_FAILED_INVALID_APK,
16079                            "New package fails restrict-update check: " + pkgName);
16080                    return;
16081                }
16082                // retain upgrade restriction
16083                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16084            }
16085
16086            // Check for shared user id changes
16087            String invalidPackageName =
16088                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16089            if (invalidPackageName != null) {
16090                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16091                        "Package " + invalidPackageName + " tried to change user "
16092                                + oldPackage.mSharedUserId);
16093                return;
16094            }
16095
16096            // check if the new package supports all of the abis which the old package supports
16097            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
16098            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
16099            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
16100                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16101                        "Update to package " + pkgName + " doesn't support multi arch");
16102                return;
16103            }
16104
16105            // In case of rollback, remember per-user/profile install state
16106            allUsers = sUserManager.getUserIds();
16107            installedUsers = ps.queryInstalledUsers(allUsers, true);
16108
16109            // don't allow an upgrade from full to ephemeral
16110            if (isInstantApp) {
16111                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16112                    for (int currentUser : allUsers) {
16113                        if (!ps.getInstantApp(currentUser)) {
16114                            // can't downgrade from full to instant
16115                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16116                                    + " for user: " + currentUser);
16117                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16118                            return;
16119                        }
16120                    }
16121                } else if (!ps.getInstantApp(user.getIdentifier())) {
16122                    // can't downgrade from full to instant
16123                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16124                            + " for user: " + user.getIdentifier());
16125                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16126                    return;
16127                }
16128            }
16129        }
16130
16131        // Update what is removed
16132        res.removedInfo = new PackageRemovedInfo(this);
16133        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16134        res.removedInfo.removedPackage = oldPackage.packageName;
16135        res.removedInfo.installerPackageName = ps.installerPackageName;
16136        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16137        res.removedInfo.isUpdate = true;
16138        res.removedInfo.origUsers = installedUsers;
16139        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16140        for (int i = 0; i < installedUsers.length; i++) {
16141            final int userId = installedUsers[i];
16142            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16143        }
16144
16145        final int childCount = (oldPackage.childPackages != null)
16146                ? oldPackage.childPackages.size() : 0;
16147        for (int i = 0; i < childCount; i++) {
16148            boolean childPackageUpdated = false;
16149            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16150            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16151            if (res.addedChildPackages != null) {
16152                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16153                if (childRes != null) {
16154                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16155                    childRes.removedInfo.removedPackage = childPkg.packageName;
16156                    if (childPs != null) {
16157                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16158                    }
16159                    childRes.removedInfo.isUpdate = true;
16160                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16161                    childPackageUpdated = true;
16162                }
16163            }
16164            if (!childPackageUpdated) {
16165                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16166                childRemovedRes.removedPackage = childPkg.packageName;
16167                if (childPs != null) {
16168                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16169                }
16170                childRemovedRes.isUpdate = false;
16171                childRemovedRes.dataRemoved = true;
16172                synchronized (mPackages) {
16173                    if (childPs != null) {
16174                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16175                    }
16176                }
16177                if (res.removedInfo.removedChildPackages == null) {
16178                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16179                }
16180                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16181            }
16182        }
16183
16184        boolean sysPkg = (isSystemApp(oldPackage));
16185        if (sysPkg) {
16186            // Set the system/privileged/oem/vendor/product flags as needed
16187            final boolean privileged =
16188                    (oldPackage.applicationInfo.privateFlags
16189                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16190            final boolean oem =
16191                    (oldPackage.applicationInfo.privateFlags
16192                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16193            final boolean vendor =
16194                    (oldPackage.applicationInfo.privateFlags
16195                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
16196            final boolean product =
16197                    (oldPackage.applicationInfo.privateFlags
16198                            & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
16199            final @ParseFlags int systemParseFlags = parseFlags;
16200            final @ScanFlags int systemScanFlags = scanFlags
16201                    | SCAN_AS_SYSTEM
16202                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
16203                    | (oem ? SCAN_AS_OEM : 0)
16204                    | (vendor ? SCAN_AS_VENDOR : 0)
16205                    | (product ? SCAN_AS_PRODUCT : 0);
16206
16207            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
16208                    user, allUsers, installerPackageName, res, installReason);
16209        } else {
16210            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
16211                    user, allUsers, installerPackageName, res, installReason);
16212        }
16213    }
16214
16215    @Override
16216    public List<String> getPreviousCodePaths(String packageName) {
16217        final int callingUid = Binder.getCallingUid();
16218        final List<String> result = new ArrayList<>();
16219        if (getInstantAppPackageName(callingUid) != null) {
16220            return result;
16221        }
16222        final PackageSetting ps = mSettings.mPackages.get(packageName);
16223        if (ps != null
16224                && ps.oldCodePaths != null
16225                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
16226            result.addAll(ps.oldCodePaths);
16227        }
16228        return result;
16229    }
16230
16231    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16232            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16233            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
16234            String installerPackageName, PackageInstalledInfo res, int installReason) {
16235        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16236                + deletedPackage);
16237
16238        String pkgName = deletedPackage.packageName;
16239        boolean deletedPkg = true;
16240        boolean addedPkg = false;
16241        boolean updatedSettings = false;
16242        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16243        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16244                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16245
16246        final long origUpdateTime = (pkg.mExtras != null)
16247                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16248
16249        // First delete the existing package while retaining the data directory
16250        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16251                res.removedInfo, true, pkg)) {
16252            // If the existing package wasn't successfully deleted
16253            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16254            deletedPkg = false;
16255        } else {
16256            // Successfully deleted the old package; proceed with replace.
16257
16258            // If deleted package lived in a container, give users a chance to
16259            // relinquish resources before killing.
16260            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16261                if (DEBUG_INSTALL) {
16262                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16263                }
16264                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16265                final ArrayList<String> pkgList = new ArrayList<String>(1);
16266                pkgList.add(deletedPackage.applicationInfo.packageName);
16267                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16268            }
16269
16270            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16271                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16272
16273            try {
16274                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
16275                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16276                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16277                        installReason);
16278
16279                // Update the in-memory copy of the previous code paths.
16280                PackageSetting ps = mSettings.mPackages.get(pkgName);
16281                if (!killApp) {
16282                    if (ps.oldCodePaths == null) {
16283                        ps.oldCodePaths = new ArraySet<>();
16284                    }
16285                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16286                    if (deletedPackage.splitCodePaths != null) {
16287                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16288                    }
16289                } else {
16290                    ps.oldCodePaths = null;
16291                }
16292                if (ps.childPackageNames != null) {
16293                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16294                        final String childPkgName = ps.childPackageNames.get(i);
16295                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16296                        childPs.oldCodePaths = ps.oldCodePaths;
16297                    }
16298                }
16299                // set instant app status, but, only if it's explicitly specified
16300                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16301                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16302                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16303                prepareAppDataAfterInstallLIF(newPackage);
16304                addedPkg = true;
16305                mDexManager.notifyPackageUpdated(newPackage.packageName,
16306                        newPackage.baseCodePath, newPackage.splitCodePaths);
16307            } catch (PackageManagerException e) {
16308                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16309            }
16310        }
16311
16312        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16313            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16314
16315            // Revert all internal state mutations and added folders for the failed install
16316            if (addedPkg) {
16317                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16318                        res.removedInfo, true, null);
16319            }
16320
16321            // Restore the old package
16322            if (deletedPkg) {
16323                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16324                File restoreFile = new File(deletedPackage.codePath);
16325                // Parse old package
16326                boolean oldExternal = isExternal(deletedPackage);
16327                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16328                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16329                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16330                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16331                try {
16332                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16333                            null);
16334                } catch (PackageManagerException e) {
16335                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16336                            + e.getMessage());
16337                    return;
16338                }
16339
16340                synchronized (mPackages) {
16341                    // Ensure the installer package name up to date
16342                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16343
16344                    // Update permissions for restored package
16345                    mPermissionManager.updatePermissions(
16346                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16347                            mPermissionCallback);
16348
16349                    mSettings.writeLPr();
16350                }
16351
16352                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16353            }
16354        } else {
16355            synchronized (mPackages) {
16356                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16357                if (ps != null) {
16358                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16359                    if (res.removedInfo.removedChildPackages != null) {
16360                        final int childCount = res.removedInfo.removedChildPackages.size();
16361                        // Iterate in reverse as we may modify the collection
16362                        for (int i = childCount - 1; i >= 0; i--) {
16363                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16364                            if (res.addedChildPackages.containsKey(childPackageName)) {
16365                                res.removedInfo.removedChildPackages.removeAt(i);
16366                            } else {
16367                                PackageRemovedInfo childInfo = res.removedInfo
16368                                        .removedChildPackages.valueAt(i);
16369                                childInfo.removedForAllUsers = mPackages.get(
16370                                        childInfo.removedPackage) == null;
16371                            }
16372                        }
16373                    }
16374                }
16375            }
16376        }
16377    }
16378
16379    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16380            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16381            final @ScanFlags int scanFlags, UserHandle user,
16382            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16383            int installReason) {
16384        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16385                + ", old=" + deletedPackage);
16386
16387        final boolean disabledSystem;
16388
16389        // Remove existing system package
16390        removePackageLI(deletedPackage, true);
16391
16392        synchronized (mPackages) {
16393            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16394        }
16395        if (!disabledSystem) {
16396            // We didn't need to disable the .apk as a current system package,
16397            // which means we are replacing another update that is already
16398            // installed.  We need to make sure to delete the older one's .apk.
16399            res.removedInfo.args = createInstallArgsForExisting(0,
16400                    deletedPackage.applicationInfo.getCodePath(),
16401                    deletedPackage.applicationInfo.getResourcePath(),
16402                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16403        } else {
16404            res.removedInfo.args = null;
16405        }
16406
16407        // Successfully disabled the old package. Now proceed with re-installation
16408        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16409                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16410
16411        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16412        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16413                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16414
16415        PackageParser.Package newPackage = null;
16416        try {
16417            // Add the package to the internal data structures
16418            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16419
16420            // Set the update and install times
16421            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16422            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16423                    System.currentTimeMillis());
16424
16425            // Update the package dynamic state if succeeded
16426            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16427                // Now that the install succeeded make sure we remove data
16428                // directories for any child package the update removed.
16429                final int deletedChildCount = (deletedPackage.childPackages != null)
16430                        ? deletedPackage.childPackages.size() : 0;
16431                final int newChildCount = (newPackage.childPackages != null)
16432                        ? newPackage.childPackages.size() : 0;
16433                for (int i = 0; i < deletedChildCount; i++) {
16434                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16435                    boolean childPackageDeleted = true;
16436                    for (int j = 0; j < newChildCount; j++) {
16437                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16438                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16439                            childPackageDeleted = false;
16440                            break;
16441                        }
16442                    }
16443                    if (childPackageDeleted) {
16444                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16445                                deletedChildPkg.packageName);
16446                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16447                            PackageRemovedInfo removedChildRes = res.removedInfo
16448                                    .removedChildPackages.get(deletedChildPkg.packageName);
16449                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16450                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16451                        }
16452                    }
16453                }
16454
16455                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16456                        installReason);
16457                prepareAppDataAfterInstallLIF(newPackage);
16458
16459                mDexManager.notifyPackageUpdated(newPackage.packageName,
16460                            newPackage.baseCodePath, newPackage.splitCodePaths);
16461            }
16462        } catch (PackageManagerException e) {
16463            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16464            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16465        }
16466
16467        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16468            // Re installation failed. Restore old information
16469            // Remove new pkg information
16470            if (newPackage != null) {
16471                removeInstalledPackageLI(newPackage, true);
16472            }
16473            // Add back the old system package
16474            try {
16475                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16476            } catch (PackageManagerException e) {
16477                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16478            }
16479
16480            synchronized (mPackages) {
16481                if (disabledSystem) {
16482                    enableSystemPackageLPw(deletedPackage);
16483                }
16484
16485                // Ensure the installer package name up to date
16486                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16487
16488                // Update permissions for restored package
16489                mPermissionManager.updatePermissions(
16490                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16491                        mPermissionCallback);
16492
16493                mSettings.writeLPr();
16494            }
16495
16496            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16497                    + " after failed upgrade");
16498        }
16499    }
16500
16501    /**
16502     * Checks whether the parent or any of the child packages have a change shared
16503     * user. For a package to be a valid update the shred users of the parent and
16504     * the children should match. We may later support changing child shared users.
16505     * @param oldPkg The updated package.
16506     * @param newPkg The update package.
16507     * @return The shared user that change between the versions.
16508     */
16509    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16510            PackageParser.Package newPkg) {
16511        // Check parent shared user
16512        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16513            return newPkg.packageName;
16514        }
16515        // Check child shared users
16516        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16517        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16518        for (int i = 0; i < newChildCount; i++) {
16519            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16520            // If this child was present, did it have the same shared user?
16521            for (int j = 0; j < oldChildCount; j++) {
16522                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16523                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16524                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16525                    return newChildPkg.packageName;
16526                }
16527            }
16528        }
16529        return null;
16530    }
16531
16532    private void removeNativeBinariesLI(PackageSetting ps) {
16533        // Remove the lib path for the parent package
16534        if (ps != null) {
16535            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16536            // Remove the lib path for the child packages
16537            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16538            for (int i = 0; i < childCount; i++) {
16539                PackageSetting childPs = null;
16540                synchronized (mPackages) {
16541                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16542                }
16543                if (childPs != null) {
16544                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16545                            .legacyNativeLibraryPathString);
16546                }
16547            }
16548        }
16549    }
16550
16551    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16552        // Enable the parent package
16553        mSettings.enableSystemPackageLPw(pkg.packageName);
16554        // Enable the child packages
16555        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16556        for (int i = 0; i < childCount; i++) {
16557            PackageParser.Package childPkg = pkg.childPackages.get(i);
16558            mSettings.enableSystemPackageLPw(childPkg.packageName);
16559        }
16560    }
16561
16562    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16563            PackageParser.Package newPkg) {
16564        // Disable the parent package (parent always replaced)
16565        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16566        // Disable the child packages
16567        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16568        for (int i = 0; i < childCount; i++) {
16569            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16570            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16571            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16572        }
16573        return disabled;
16574    }
16575
16576    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16577            String installerPackageName) {
16578        // Enable the parent package
16579        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16580        // Enable the child packages
16581        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16582        for (int i = 0; i < childCount; i++) {
16583            PackageParser.Package childPkg = pkg.childPackages.get(i);
16584            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16585        }
16586    }
16587
16588    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16589            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16590        // Update the parent package setting
16591        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16592                res, user, installReason);
16593        // Update the child packages setting
16594        final int childCount = (newPackage.childPackages != null)
16595                ? newPackage.childPackages.size() : 0;
16596        for (int i = 0; i < childCount; i++) {
16597            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16598            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16599            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16600                    childRes.origUsers, childRes, user, installReason);
16601        }
16602    }
16603
16604    private void updateSettingsInternalLI(PackageParser.Package pkg,
16605            String installerPackageName, int[] allUsers, int[] installedForUsers,
16606            PackageInstalledInfo res, UserHandle user, int installReason) {
16607        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16608
16609        String pkgName = pkg.packageName;
16610        synchronized (mPackages) {
16611            //write settings. the installStatus will be incomplete at this stage.
16612            //note that the new package setting would have already been
16613            //added to mPackages. It hasn't been persisted yet.
16614            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16615            // TODO: Remove this write? It's also written at the end of this method
16616            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16617            mSettings.writeLPr();
16618            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16619        }
16620
16621        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16622        synchronized (mPackages) {
16623// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16624            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16625                    mPermissionCallback);
16626            // For system-bundled packages, we assume that installing an upgraded version
16627            // of the package implies that the user actually wants to run that new code,
16628            // so we enable the package.
16629            PackageSetting ps = mSettings.mPackages.get(pkgName);
16630            final int userId = user.getIdentifier();
16631            if (ps != null) {
16632                if (isSystemApp(pkg)) {
16633                    if (DEBUG_INSTALL) {
16634                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16635                    }
16636                    // Enable system package for requested users
16637                    if (res.origUsers != null) {
16638                        for (int origUserId : res.origUsers) {
16639                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16640                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16641                                        origUserId, installerPackageName);
16642                            }
16643                        }
16644                    }
16645                    // Also convey the prior install/uninstall state
16646                    if (allUsers != null && installedForUsers != null) {
16647                        for (int currentUserId : allUsers) {
16648                            final boolean installed = ArrayUtils.contains(
16649                                    installedForUsers, currentUserId);
16650                            if (DEBUG_INSTALL) {
16651                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16652                            }
16653                            ps.setInstalled(installed, currentUserId);
16654                        }
16655                        // these install state changes will be persisted in the
16656                        // upcoming call to mSettings.writeLPr().
16657                    }
16658                }
16659                // It's implied that when a user requests installation, they want the app to be
16660                // installed and enabled.
16661                if (userId != UserHandle.USER_ALL) {
16662                    ps.setInstalled(true, userId);
16663                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16664                }
16665
16666                // When replacing an existing package, preserve the original install reason for all
16667                // users that had the package installed before.
16668                final Set<Integer> previousUserIds = new ArraySet<>();
16669                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16670                    final int installReasonCount = res.removedInfo.installReasons.size();
16671                    for (int i = 0; i < installReasonCount; i++) {
16672                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16673                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16674                        ps.setInstallReason(previousInstallReason, previousUserId);
16675                        previousUserIds.add(previousUserId);
16676                    }
16677                }
16678
16679                // Set install reason for users that are having the package newly installed.
16680                if (userId == UserHandle.USER_ALL) {
16681                    for (int currentUserId : sUserManager.getUserIds()) {
16682                        if (!previousUserIds.contains(currentUserId)) {
16683                            ps.setInstallReason(installReason, currentUserId);
16684                        }
16685                    }
16686                } else if (!previousUserIds.contains(userId)) {
16687                    ps.setInstallReason(installReason, userId);
16688                }
16689                mSettings.writeKernelMappingLPr(ps);
16690            }
16691            res.name = pkgName;
16692            res.uid = pkg.applicationInfo.uid;
16693            res.pkg = pkg;
16694            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16695            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16696            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16697            //to update install status
16698            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16699            mSettings.writeLPr();
16700            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16701        }
16702
16703        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16704    }
16705
16706    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16707        try {
16708            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16709            installPackageLI(args, res);
16710        } finally {
16711            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16712        }
16713    }
16714
16715    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16716        final int installFlags = args.installFlags;
16717        final String installerPackageName = args.installerPackageName;
16718        final String volumeUuid = args.volumeUuid;
16719        final File tmpPackageFile = new File(args.getCodePath());
16720        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16721        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16722                || (args.volumeUuid != null));
16723        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16724        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16725        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16726        final boolean virtualPreload =
16727                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16728        boolean replace = false;
16729        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16730        if (args.move != null) {
16731            // moving a complete application; perform an initial scan on the new install location
16732            scanFlags |= SCAN_INITIAL;
16733        }
16734        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16735            scanFlags |= SCAN_DONT_KILL_APP;
16736        }
16737        if (instantApp) {
16738            scanFlags |= SCAN_AS_INSTANT_APP;
16739        }
16740        if (fullApp) {
16741            scanFlags |= SCAN_AS_FULL_APP;
16742        }
16743        if (virtualPreload) {
16744            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16745        }
16746
16747        // Result object to be returned
16748        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16749        res.installerPackageName = installerPackageName;
16750
16751        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16752
16753        // Sanity check
16754        if (instantApp && (forwardLocked || onExternal)) {
16755            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16756                    + " external=" + onExternal);
16757            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16758            return;
16759        }
16760
16761        // Retrieve PackageSettings and parse package
16762        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16763                | PackageParser.PARSE_ENFORCE_CODE
16764                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16765                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16766                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16767        PackageParser pp = new PackageParser();
16768        pp.setSeparateProcesses(mSeparateProcesses);
16769        pp.setDisplayMetrics(mMetrics);
16770        pp.setCallback(mPackageParserCallback);
16771
16772        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16773        final PackageParser.Package pkg;
16774        try {
16775            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16776            DexMetadataHelper.validatePackageDexMetadata(pkg);
16777        } catch (PackageParserException e) {
16778            res.setError("Failed parse during installPackageLI", e);
16779            return;
16780        } finally {
16781            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16782        }
16783
16784        // Instant apps have several additional install-time checks.
16785        if (instantApp) {
16786            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
16787                Slog.w(TAG,
16788                        "Instant app package " + pkg.packageName + " does not target at least O");
16789                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16790                        "Instant app package must target at least O");
16791                return;
16792            }
16793            if (pkg.applicationInfo.targetSandboxVersion != 2) {
16794                Slog.w(TAG, "Instant app package " + pkg.packageName
16795                        + " does not target targetSandboxVersion 2");
16796                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16797                        "Instant app package must use targetSandboxVersion 2");
16798                return;
16799            }
16800            if (pkg.mSharedUserId != null) {
16801                Slog.w(TAG, "Instant app package " + pkg.packageName
16802                        + " may not declare sharedUserId.");
16803                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16804                        "Instant app package may not declare a sharedUserId");
16805                return;
16806            }
16807        }
16808
16809        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16810            // Static shared libraries have synthetic package names
16811            renameStaticSharedLibraryPackage(pkg);
16812
16813            // No static shared libs on external storage
16814            if (onExternal) {
16815                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16816                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16817                        "Packages declaring static-shared libs cannot be updated");
16818                return;
16819            }
16820        }
16821
16822        // If we are installing a clustered package add results for the children
16823        if (pkg.childPackages != null) {
16824            synchronized (mPackages) {
16825                final int childCount = pkg.childPackages.size();
16826                for (int i = 0; i < childCount; i++) {
16827                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16828                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16829                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16830                    childRes.pkg = childPkg;
16831                    childRes.name = childPkg.packageName;
16832                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16833                    if (childPs != null) {
16834                        childRes.origUsers = childPs.queryInstalledUsers(
16835                                sUserManager.getUserIds(), true);
16836                    }
16837                    if ((mPackages.containsKey(childPkg.packageName))) {
16838                        childRes.removedInfo = new PackageRemovedInfo(this);
16839                        childRes.removedInfo.removedPackage = childPkg.packageName;
16840                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16841                    }
16842                    if (res.addedChildPackages == null) {
16843                        res.addedChildPackages = new ArrayMap<>();
16844                    }
16845                    res.addedChildPackages.put(childPkg.packageName, childRes);
16846                }
16847            }
16848        }
16849
16850        // If package doesn't declare API override, mark that we have an install
16851        // time CPU ABI override.
16852        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16853            pkg.cpuAbiOverride = args.abiOverride;
16854        }
16855
16856        String pkgName = res.name = pkg.packageName;
16857        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16858            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16859                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16860                return;
16861            }
16862        }
16863
16864        try {
16865            // either use what we've been given or parse directly from the APK
16866            if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
16867                pkg.setSigningDetails(args.signingDetails);
16868            } else {
16869                PackageParser.collectCertificates(pkg, false /* skipVerify */);
16870            }
16871        } catch (PackageParserException e) {
16872            res.setError("Failed collect during installPackageLI", e);
16873            return;
16874        }
16875
16876        if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
16877                < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
16878            Slog.w(TAG, "Instant app package " + pkg.packageName
16879                    + " is not signed with at least APK Signature Scheme v2");
16880            res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16881                    "Instant app package must be signed with APK Signature Scheme v2 or greater");
16882            return;
16883        }
16884
16885        // Get rid of all references to package scan path via parser.
16886        pp = null;
16887        String oldCodePath = null;
16888        boolean systemApp = false;
16889        synchronized (mPackages) {
16890            // Check if installing already existing package
16891            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16892                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16893                if (pkg.mOriginalPackages != null
16894                        && pkg.mOriginalPackages.contains(oldName)
16895                        && mPackages.containsKey(oldName)) {
16896                    // This package is derived from an original package,
16897                    // and this device has been updating from that original
16898                    // name.  We must continue using the original name, so
16899                    // rename the new package here.
16900                    pkg.setPackageName(oldName);
16901                    pkgName = pkg.packageName;
16902                    replace = true;
16903                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16904                            + oldName + " pkgName=" + pkgName);
16905                } else if (mPackages.containsKey(pkgName)) {
16906                    // This package, under its official name, already exists
16907                    // on the device; we should replace it.
16908                    replace = true;
16909                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16910                }
16911
16912                // Child packages are installed through the parent package
16913                if (pkg.parentPackage != null) {
16914                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16915                            "Package " + pkg.packageName + " is child of package "
16916                                    + pkg.parentPackage.parentPackage + ". Child packages "
16917                                    + "can be updated only through the parent package.");
16918                    return;
16919                }
16920
16921                if (replace) {
16922                    // Prevent apps opting out from runtime permissions
16923                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16924                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16925                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16926                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16927                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16928                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16929                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16930                                        + " doesn't support runtime permissions but the old"
16931                                        + " target SDK " + oldTargetSdk + " does.");
16932                        return;
16933                    }
16934                    // Prevent persistent apps from being updated
16935                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
16936                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
16937                                "Package " + oldPackage.packageName + " is a persistent app. "
16938                                        + "Persistent apps are not updateable.");
16939                        return;
16940                    }
16941                    // Prevent apps from downgrading their targetSandbox.
16942                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16943                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16944                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16945                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16946                                "Package " + pkg.packageName + " new target sandbox "
16947                                + newTargetSandbox + " is incompatible with the previous value of"
16948                                + oldTargetSandbox + ".");
16949                        return;
16950                    }
16951
16952                    // Prevent installing of child packages
16953                    if (oldPackage.parentPackage != null) {
16954                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16955                                "Package " + pkg.packageName + " is child of package "
16956                                        + oldPackage.parentPackage + ". Child packages "
16957                                        + "can be updated only through the parent package.");
16958                        return;
16959                    }
16960                }
16961            }
16962
16963            PackageSetting ps = mSettings.mPackages.get(pkgName);
16964            if (ps != null) {
16965                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16966
16967                // Static shared libs have same package with different versions where
16968                // we internally use a synthetic package name to allow multiple versions
16969                // of the same package, therefore we need to compare signatures against
16970                // the package setting for the latest library version.
16971                PackageSetting signatureCheckPs = ps;
16972                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16973                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16974                    if (libraryEntry != null) {
16975                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16976                    }
16977                }
16978
16979                // Quick sanity check that we're signed correctly if updating;
16980                // we'll check this again later when scanning, but we want to
16981                // bail early here before tripping over redefined permissions.
16982                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16983                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
16984                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
16985                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16986                                + pkg.packageName + " upgrade keys do not match the "
16987                                + "previously installed version");
16988                        return;
16989                    }
16990                } else {
16991                    try {
16992                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
16993                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
16994                        // We don't care about disabledPkgSetting on install for now.
16995                        final boolean compatMatch = verifySignatures(
16996                                signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
16997                                compareRecover);
16998                        // The new KeySets will be re-added later in the scanning process.
16999                        if (compatMatch) {
17000                            synchronized (mPackages) {
17001                                ksms.removeAppKeySetDataLPw(pkg.packageName);
17002                            }
17003                        }
17004                    } catch (PackageManagerException e) {
17005                        res.setError(e.error, e.getMessage());
17006                        return;
17007                    }
17008                }
17009
17010                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17011                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17012                    systemApp = (ps.pkg.applicationInfo.flags &
17013                            ApplicationInfo.FLAG_SYSTEM) != 0;
17014                }
17015                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17016            }
17017
17018            int N = pkg.permissions.size();
17019            for (int i = N-1; i >= 0; i--) {
17020                final PackageParser.Permission perm = pkg.permissions.get(i);
17021                final BasePermission bp =
17022                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
17023
17024                // Don't allow anyone but the system to define ephemeral permissions.
17025                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
17026                        && !systemApp) {
17027                    Slog.w(TAG, "Non-System package " + pkg.packageName
17028                            + " attempting to delcare ephemeral permission "
17029                            + perm.info.name + "; Removing ephemeral.");
17030                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
17031                }
17032
17033                // Check whether the newly-scanned package wants to define an already-defined perm
17034                if (bp != null) {
17035                    // If the defining package is signed with our cert, it's okay.  This
17036                    // also includes the "updating the same package" case, of course.
17037                    // "updating same package" could also involve key-rotation.
17038                    final boolean sigsOk;
17039                    final String sourcePackageName = bp.getSourcePackageName();
17040                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17041                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17042                    if (sourcePackageName.equals(pkg.packageName)
17043                            && (ksms.shouldCheckUpgradeKeySetLocked(
17044                                    sourcePackageSetting, scanFlags))) {
17045                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
17046                    } else {
17047                        sigsOk = compareSignatures(
17048                                sourcePackageSetting.signatures.mSigningDetails.signatures,
17049                                pkg.mSigningDetails.signatures) == PackageManager.SIGNATURE_MATCH;
17050                    }
17051                    if (!sigsOk) {
17052                        // If the owning package is the system itself, we log but allow
17053                        // install to proceed; we fail the install on all other permission
17054                        // redefinitions.
17055                        if (!sourcePackageName.equals("android")) {
17056                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17057                                    + pkg.packageName + " attempting to redeclare permission "
17058                                    + perm.info.name + " already owned by " + sourcePackageName);
17059                            res.origPermission = perm.info.name;
17060                            res.origPackage = sourcePackageName;
17061                            return;
17062                        } else {
17063                            Slog.w(TAG, "Package " + pkg.packageName
17064                                    + " attempting to redeclare system permission "
17065                                    + perm.info.name + "; ignoring new declaration");
17066                            pkg.permissions.remove(i);
17067                        }
17068                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17069                        // Prevent apps to change protection level to dangerous from any other
17070                        // type as this would allow a privilege escalation where an app adds a
17071                        // normal/signature permission in other app's group and later redefines
17072                        // it as dangerous leading to the group auto-grant.
17073                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17074                                == PermissionInfo.PROTECTION_DANGEROUS) {
17075                            if (bp != null && !bp.isRuntime()) {
17076                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17077                                        + "non-runtime permission " + perm.info.name
17078                                        + " to runtime; keeping old protection level");
17079                                perm.info.protectionLevel = bp.getProtectionLevel();
17080                            }
17081                        }
17082                    }
17083                }
17084            }
17085        }
17086
17087        if (systemApp) {
17088            if (onExternal) {
17089                // Abort update; system app can't be replaced with app on sdcard
17090                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17091                        "Cannot install updates to system apps on sdcard");
17092                return;
17093            } else if (instantApp) {
17094                // Abort update; system app can't be replaced with an instant app
17095                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17096                        "Cannot update a system app with an instant app");
17097                return;
17098            }
17099        }
17100
17101        if (args.move != null) {
17102            // We did an in-place move, so dex is ready to roll
17103            scanFlags |= SCAN_NO_DEX;
17104            scanFlags |= SCAN_MOVE;
17105
17106            synchronized (mPackages) {
17107                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17108                if (ps == null) {
17109                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17110                            "Missing settings for moved package " + pkgName);
17111                }
17112
17113                // We moved the entire application as-is, so bring over the
17114                // previously derived ABI information.
17115                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17116                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17117            }
17118
17119        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17120            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17121            scanFlags |= SCAN_NO_DEX;
17122
17123            try {
17124                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17125                    args.abiOverride : pkg.cpuAbiOverride);
17126                final boolean extractNativeLibs = !pkg.isLibrary();
17127                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
17128            } catch (PackageManagerException pme) {
17129                Slog.e(TAG, "Error deriving application ABI", pme);
17130                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17131                return;
17132            }
17133
17134            // Shared libraries for the package need to be updated.
17135            synchronized (mPackages) {
17136                try {
17137                    updateSharedLibrariesLPr(pkg, null);
17138                } catch (PackageManagerException e) {
17139                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17140                }
17141            }
17142        }
17143
17144        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17145            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17146            return;
17147        }
17148
17149        if (PackageManagerServiceUtils.isApkVerityEnabled()) {
17150            String apkPath = null;
17151            synchronized (mPackages) {
17152                // Note that if the attacker managed to skip verify setup, for example by tampering
17153                // with the package settings, upon reboot we will do full apk verification when
17154                // verity is not detected.
17155                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17156                if (ps != null && ps.isPrivileged()) {
17157                    apkPath = pkg.baseCodePath;
17158                }
17159            }
17160
17161            if (apkPath != null) {
17162                final VerityUtils.SetupResult result =
17163                        VerityUtils.generateApkVeritySetupData(apkPath);
17164                if (result.isOk()) {
17165                    if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath);
17166                    FileDescriptor fd = result.getUnownedFileDescriptor();
17167                    try {
17168                        mInstaller.installApkVerity(apkPath, fd);
17169                    } catch (InstallerException e) {
17170                        res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17171                                "Failed to set up verity: " + e);
17172                        return;
17173                    } finally {
17174                        IoUtils.closeQuietly(fd);
17175                    }
17176                } else if (result.isFailed()) {
17177                    res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity");
17178                    return;
17179                } else {
17180                    // Do nothing if verity is skipped. Will fall back to full apk verification on
17181                    // reboot.
17182                }
17183            }
17184        }
17185
17186        if (!instantApp) {
17187            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17188        } else {
17189            if (DEBUG_DOMAIN_VERIFICATION) {
17190                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17191            }
17192        }
17193
17194        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17195                "installPackageLI")) {
17196            if (replace) {
17197                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17198                    // Static libs have a synthetic package name containing the version
17199                    // and cannot be updated as an update would get a new package name,
17200                    // unless this is the exact same version code which is useful for
17201                    // development.
17202                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17203                    if (existingPkg != null &&
17204                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
17205                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17206                                + "static-shared libs cannot be updated");
17207                        return;
17208                    }
17209                }
17210                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
17211                        installerPackageName, res, args.installReason);
17212            } else {
17213                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17214                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17215            }
17216        }
17217
17218        // Prepare the application profiles for the new code paths.
17219        // This needs to be done before invoking dexopt so that any install-time profile
17220        // can be used for optimizations.
17221        mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier()));
17222
17223        // Check whether we need to dexopt the app.
17224        //
17225        // NOTE: it is IMPORTANT to call dexopt:
17226        //   - after doRename which will sync the package data from PackageParser.Package and its
17227        //     corresponding ApplicationInfo.
17228        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
17229        //     uid of the application (pkg.applicationInfo.uid).
17230        //     This update happens in place!
17231        //
17232        // We only need to dexopt if the package meets ALL of the following conditions:
17233        //   1) it is not forward locked.
17234        //   2) it is not on on an external ASEC container.
17235        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17236        //
17237        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17238        // complete, so we skip this step during installation. Instead, we'll take extra time
17239        // the first time the instant app starts. It's preferred to do it this way to provide
17240        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17241        // middle of running an instant app. The default behaviour can be overridden
17242        // via gservices.
17243        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
17244                && !forwardLocked
17245                && !pkg.applicationInfo.isExternalAsec()
17246                && (!instantApp || Global.getInt(mContext.getContentResolver(),
17247                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
17248
17249        if (performDexopt) {
17250            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17251            // Do not run PackageDexOptimizer through the local performDexOpt
17252            // method because `pkg` may not be in `mPackages` yet.
17253            //
17254            // Also, don't fail application installs if the dexopt step fails.
17255            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17256                    REASON_INSTALL,
17257                    DexoptOptions.DEXOPT_BOOT_COMPLETE);
17258            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17259                    null /* instructionSets */,
17260                    getOrCreateCompilerPackageStats(pkg),
17261                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17262                    dexoptOptions);
17263            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17264        }
17265
17266        // Notify BackgroundDexOptService that the package has been changed.
17267        // If this is an update of a package which used to fail to compile,
17268        // BackgroundDexOptService will remove it from its blacklist.
17269        // TODO: Layering violation
17270        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17271
17272        synchronized (mPackages) {
17273            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17274            if (ps != null) {
17275                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17276                ps.setUpdateAvailable(false /*updateAvailable*/);
17277            }
17278
17279            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17280            for (int i = 0; i < childCount; i++) {
17281                PackageParser.Package childPkg = pkg.childPackages.get(i);
17282                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17283                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17284                if (childPs != null) {
17285                    childRes.newUsers = childPs.queryInstalledUsers(
17286                            sUserManager.getUserIds(), true);
17287                }
17288            }
17289
17290            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17291                updateSequenceNumberLP(ps, res.newUsers);
17292                updateInstantAppInstallerLocked(pkgName);
17293            }
17294        }
17295    }
17296
17297    private void startIntentFilterVerifications(int userId, boolean replacing,
17298            PackageParser.Package pkg) {
17299        if (mIntentFilterVerifierComponent == null) {
17300            Slog.w(TAG, "No IntentFilter verification will not be done as "
17301                    + "there is no IntentFilterVerifier available!");
17302            return;
17303        }
17304
17305        final int verifierUid = getPackageUid(
17306                mIntentFilterVerifierComponent.getPackageName(),
17307                MATCH_DEBUG_TRIAGED_MISSING,
17308                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17309
17310        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17311        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17312        mHandler.sendMessage(msg);
17313
17314        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17315        for (int i = 0; i < childCount; i++) {
17316            PackageParser.Package childPkg = pkg.childPackages.get(i);
17317            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17318            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17319            mHandler.sendMessage(msg);
17320        }
17321    }
17322
17323    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17324            PackageParser.Package pkg) {
17325        int size = pkg.activities.size();
17326        if (size == 0) {
17327            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17328                    "No activity, so no need to verify any IntentFilter!");
17329            return;
17330        }
17331
17332        final boolean hasDomainURLs = hasDomainURLs(pkg);
17333        if (!hasDomainURLs) {
17334            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17335                    "No domain URLs, so no need to verify any IntentFilter!");
17336            return;
17337        }
17338
17339        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17340                + " if any IntentFilter from the " + size
17341                + " Activities needs verification ...");
17342
17343        int count = 0;
17344        final String packageName = pkg.packageName;
17345
17346        synchronized (mPackages) {
17347            // If this is a new install and we see that we've already run verification for this
17348            // package, we have nothing to do: it means the state was restored from backup.
17349            if (!replacing) {
17350                IntentFilterVerificationInfo ivi =
17351                        mSettings.getIntentFilterVerificationLPr(packageName);
17352                if (ivi != null) {
17353                    if (DEBUG_DOMAIN_VERIFICATION) {
17354                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17355                                + ivi.getStatusString());
17356                    }
17357                    return;
17358                }
17359            }
17360
17361            // If any filters need to be verified, then all need to be.
17362            boolean needToVerify = false;
17363            for (PackageParser.Activity a : pkg.activities) {
17364                for (ActivityIntentInfo filter : a.intents) {
17365                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17366                        if (DEBUG_DOMAIN_VERIFICATION) {
17367                            Slog.d(TAG,
17368                                    "Intent filter needs verification, so processing all filters");
17369                        }
17370                        needToVerify = true;
17371                        break;
17372                    }
17373                }
17374            }
17375
17376            if (needToVerify) {
17377                final int verificationId = mIntentFilterVerificationToken++;
17378                for (PackageParser.Activity a : pkg.activities) {
17379                    for (ActivityIntentInfo filter : a.intents) {
17380                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17381                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17382                                    "Verification needed for IntentFilter:" + filter.toString());
17383                            mIntentFilterVerifier.addOneIntentFilterVerification(
17384                                    verifierUid, userId, verificationId, filter, packageName);
17385                            count++;
17386                        }
17387                    }
17388                }
17389            }
17390        }
17391
17392        if (count > 0) {
17393            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17394                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17395                    +  " for userId:" + userId);
17396            mIntentFilterVerifier.startVerifications(userId);
17397        } else {
17398            if (DEBUG_DOMAIN_VERIFICATION) {
17399                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17400            }
17401        }
17402    }
17403
17404    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17405        final ComponentName cn  = filter.activity.getComponentName();
17406        final String packageName = cn.getPackageName();
17407
17408        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17409                packageName);
17410        if (ivi == null) {
17411            return true;
17412        }
17413        int status = ivi.getStatus();
17414        switch (status) {
17415            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17416            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17417                return true;
17418
17419            default:
17420                // Nothing to do
17421                return false;
17422        }
17423    }
17424
17425    private static boolean isMultiArch(ApplicationInfo info) {
17426        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17427    }
17428
17429    private static boolean isExternal(PackageParser.Package pkg) {
17430        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17431    }
17432
17433    private static boolean isExternal(PackageSetting ps) {
17434        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17435    }
17436
17437    private static boolean isSystemApp(PackageParser.Package pkg) {
17438        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17439    }
17440
17441    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17442        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17443    }
17444
17445    private static boolean isOemApp(PackageParser.Package pkg) {
17446        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17447    }
17448
17449    private static boolean isVendorApp(PackageParser.Package pkg) {
17450        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17451    }
17452
17453    private static boolean isProductApp(PackageParser.Package pkg) {
17454        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
17455    }
17456
17457    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17458        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17459    }
17460
17461    private static boolean isSystemApp(PackageSetting ps) {
17462        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17463    }
17464
17465    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17466        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17467    }
17468
17469    private int packageFlagsToInstallFlags(PackageSetting ps) {
17470        int installFlags = 0;
17471        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17472            // This existing package was an external ASEC install when we have
17473            // the external flag without a UUID
17474            installFlags |= PackageManager.INSTALL_EXTERNAL;
17475        }
17476        if (ps.isForwardLocked()) {
17477            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17478        }
17479        return installFlags;
17480    }
17481
17482    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17483        if (isExternal(pkg)) {
17484            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17485                return mSettings.getExternalVersion();
17486            } else {
17487                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17488            }
17489        } else {
17490            return mSettings.getInternalVersion();
17491        }
17492    }
17493
17494    private void deleteTempPackageFiles() {
17495        final FilenameFilter filter = new FilenameFilter() {
17496            public boolean accept(File dir, String name) {
17497                return name.startsWith("vmdl") && name.endsWith(".tmp");
17498            }
17499        };
17500        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17501            file.delete();
17502        }
17503    }
17504
17505    @Override
17506    public void deletePackageAsUser(String packageName, int versionCode,
17507            IPackageDeleteObserver observer, int userId, int flags) {
17508        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17509                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17510    }
17511
17512    @Override
17513    public void deletePackageVersioned(VersionedPackage versionedPackage,
17514            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17515        final int callingUid = Binder.getCallingUid();
17516        mContext.enforceCallingOrSelfPermission(
17517                android.Manifest.permission.DELETE_PACKAGES, null);
17518        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17519        Preconditions.checkNotNull(versionedPackage);
17520        Preconditions.checkNotNull(observer);
17521        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17522                PackageManager.VERSION_CODE_HIGHEST,
17523                Long.MAX_VALUE, "versionCode must be >= -1");
17524
17525        final String packageName = versionedPackage.getPackageName();
17526        final long versionCode = versionedPackage.getLongVersionCode();
17527        final String internalPackageName;
17528        synchronized (mPackages) {
17529            // Normalize package name to handle renamed packages and static libs
17530            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17531        }
17532
17533        final int uid = Binder.getCallingUid();
17534        if (!isOrphaned(internalPackageName)
17535                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17536            try {
17537                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17538                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17539                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17540                observer.onUserActionRequired(intent);
17541            } catch (RemoteException re) {
17542            }
17543            return;
17544        }
17545        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17546        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17547        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17548            mContext.enforceCallingOrSelfPermission(
17549                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17550                    "deletePackage for user " + userId);
17551        }
17552
17553        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17554            try {
17555                observer.onPackageDeleted(packageName,
17556                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17557            } catch (RemoteException re) {
17558            }
17559            return;
17560        }
17561
17562        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17563            try {
17564                observer.onPackageDeleted(packageName,
17565                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17566            } catch (RemoteException re) {
17567            }
17568            return;
17569        }
17570
17571        if (DEBUG_REMOVE) {
17572            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17573                    + " deleteAllUsers: " + deleteAllUsers + " version="
17574                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17575                    ? "VERSION_CODE_HIGHEST" : versionCode));
17576        }
17577        // Queue up an async operation since the package deletion may take a little while.
17578        mHandler.post(new Runnable() {
17579            public void run() {
17580                mHandler.removeCallbacks(this);
17581                int returnCode;
17582                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17583                boolean doDeletePackage = true;
17584                if (ps != null) {
17585                    final boolean targetIsInstantApp =
17586                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17587                    doDeletePackage = !targetIsInstantApp
17588                            || canViewInstantApps;
17589                }
17590                if (doDeletePackage) {
17591                    if (!deleteAllUsers) {
17592                        returnCode = deletePackageX(internalPackageName, versionCode,
17593                                userId, deleteFlags);
17594                    } else {
17595                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17596                                internalPackageName, users);
17597                        // If nobody is blocking uninstall, proceed with delete for all users
17598                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17599                            returnCode = deletePackageX(internalPackageName, versionCode,
17600                                    userId, deleteFlags);
17601                        } else {
17602                            // Otherwise uninstall individually for users with blockUninstalls=false
17603                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17604                            for (int userId : users) {
17605                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17606                                    returnCode = deletePackageX(internalPackageName, versionCode,
17607                                            userId, userFlags);
17608                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17609                                        Slog.w(TAG, "Package delete failed for user " + userId
17610                                                + ", returnCode " + returnCode);
17611                                    }
17612                                }
17613                            }
17614                            // The app has only been marked uninstalled for certain users.
17615                            // We still need to report that delete was blocked
17616                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17617                        }
17618                    }
17619                } else {
17620                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17621                }
17622                try {
17623                    observer.onPackageDeleted(packageName, returnCode, null);
17624                } catch (RemoteException e) {
17625                    Log.i(TAG, "Observer no longer exists.");
17626                } //end catch
17627            } //end run
17628        });
17629    }
17630
17631    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17632        if (pkg.staticSharedLibName != null) {
17633            return pkg.manifestPackageName;
17634        }
17635        return pkg.packageName;
17636    }
17637
17638    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17639        // Handle renamed packages
17640        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17641        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17642
17643        // Is this a static library?
17644        LongSparseArray<SharedLibraryEntry> versionedLib =
17645                mStaticLibsByDeclaringPackage.get(packageName);
17646        if (versionedLib == null || versionedLib.size() <= 0) {
17647            return packageName;
17648        }
17649
17650        // Figure out which lib versions the caller can see
17651        LongSparseLongArray versionsCallerCanSee = null;
17652        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17653        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17654                && callingAppId != Process.ROOT_UID) {
17655            versionsCallerCanSee = new LongSparseLongArray();
17656            String libName = versionedLib.valueAt(0).info.getName();
17657            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17658            if (uidPackages != null) {
17659                for (String uidPackage : uidPackages) {
17660                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17661                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17662                    if (libIdx >= 0) {
17663                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17664                        versionsCallerCanSee.append(libVersion, libVersion);
17665                    }
17666                }
17667            }
17668        }
17669
17670        // Caller can see nothing - done
17671        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17672            return packageName;
17673        }
17674
17675        // Find the version the caller can see and the app version code
17676        SharedLibraryEntry highestVersion = null;
17677        final int versionCount = versionedLib.size();
17678        for (int i = 0; i < versionCount; i++) {
17679            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17680            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17681                    libEntry.info.getLongVersion()) < 0) {
17682                continue;
17683            }
17684            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17685            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17686                if (libVersionCode == versionCode) {
17687                    return libEntry.apk;
17688                }
17689            } else if (highestVersion == null) {
17690                highestVersion = libEntry;
17691            } else if (libVersionCode  > highestVersion.info
17692                    .getDeclaringPackage().getLongVersionCode()) {
17693                highestVersion = libEntry;
17694            }
17695        }
17696
17697        if (highestVersion != null) {
17698            return highestVersion.apk;
17699        }
17700
17701        return packageName;
17702    }
17703
17704    boolean isCallerVerifier(int callingUid) {
17705        final int callingUserId = UserHandle.getUserId(callingUid);
17706        return mRequiredVerifierPackage != null &&
17707                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17708    }
17709
17710    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17711        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17712              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17713            return true;
17714        }
17715        final int callingUserId = UserHandle.getUserId(callingUid);
17716        // If the caller installed the pkgName, then allow it to silently uninstall.
17717        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17718            return true;
17719        }
17720
17721        // Allow package verifier to silently uninstall.
17722        if (mRequiredVerifierPackage != null &&
17723                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17724            return true;
17725        }
17726
17727        // Allow package uninstaller to silently uninstall.
17728        if (mRequiredUninstallerPackage != null &&
17729                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17730            return true;
17731        }
17732
17733        // Allow storage manager to silently uninstall.
17734        if (mStorageManagerPackage != null &&
17735                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17736            return true;
17737        }
17738
17739        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17740        // uninstall for device owner provisioning.
17741        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17742                == PERMISSION_GRANTED) {
17743            return true;
17744        }
17745
17746        return false;
17747    }
17748
17749    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17750        int[] result = EMPTY_INT_ARRAY;
17751        for (int userId : userIds) {
17752            if (getBlockUninstallForUser(packageName, userId)) {
17753                result = ArrayUtils.appendInt(result, userId);
17754            }
17755        }
17756        return result;
17757    }
17758
17759    @Override
17760    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17761        final int callingUid = Binder.getCallingUid();
17762        if (getInstantAppPackageName(callingUid) != null
17763                && !isCallerSameApp(packageName, callingUid)) {
17764            return false;
17765        }
17766        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17767    }
17768
17769    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17770        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17771                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17772        try {
17773            if (dpm != null) {
17774                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17775                        /* callingUserOnly =*/ false);
17776                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17777                        : deviceOwnerComponentName.getPackageName();
17778                // Does the package contains the device owner?
17779                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17780                // this check is probably not needed, since DO should be registered as a device
17781                // admin on some user too. (Original bug for this: b/17657954)
17782                if (packageName.equals(deviceOwnerPackageName)) {
17783                    return true;
17784                }
17785                // Does it contain a device admin for any user?
17786                int[] users;
17787                if (userId == UserHandle.USER_ALL) {
17788                    users = sUserManager.getUserIds();
17789                } else {
17790                    users = new int[]{userId};
17791                }
17792                for (int i = 0; i < users.length; ++i) {
17793                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17794                        return true;
17795                    }
17796                }
17797            }
17798        } catch (RemoteException e) {
17799        }
17800        return false;
17801    }
17802
17803    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17804        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17805    }
17806
17807    /**
17808     *  This method is an internal method that could be get invoked either
17809     *  to delete an installed package or to clean up a failed installation.
17810     *  After deleting an installed package, a broadcast is sent to notify any
17811     *  listeners that the package has been removed. For cleaning up a failed
17812     *  installation, the broadcast is not necessary since the package's
17813     *  installation wouldn't have sent the initial broadcast either
17814     *  The key steps in deleting a package are
17815     *  deleting the package information in internal structures like mPackages,
17816     *  deleting the packages base directories through installd
17817     *  updating mSettings to reflect current status
17818     *  persisting settings for later use
17819     *  sending a broadcast if necessary
17820     */
17821    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
17822        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17823        final boolean res;
17824
17825        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17826                ? UserHandle.USER_ALL : userId;
17827
17828        if (isPackageDeviceAdmin(packageName, removeUser)) {
17829            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17830            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17831        }
17832
17833        PackageSetting uninstalledPs = null;
17834        PackageParser.Package pkg = null;
17835
17836        // for the uninstall-updates case and restricted profiles, remember the per-
17837        // user handle installed state
17838        int[] allUsers;
17839        synchronized (mPackages) {
17840            uninstalledPs = mSettings.mPackages.get(packageName);
17841            if (uninstalledPs == null) {
17842                Slog.w(TAG, "Not removing non-existent package " + packageName);
17843                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17844            }
17845
17846            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17847                    && uninstalledPs.versionCode != versionCode) {
17848                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17849                        + uninstalledPs.versionCode + " != " + versionCode);
17850                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17851            }
17852
17853            // Static shared libs can be declared by any package, so let us not
17854            // allow removing a package if it provides a lib others depend on.
17855            pkg = mPackages.get(packageName);
17856
17857            allUsers = sUserManager.getUserIds();
17858
17859            if (pkg != null && pkg.staticSharedLibName != null) {
17860                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17861                        pkg.staticSharedLibVersion);
17862                if (libEntry != null) {
17863                    for (int currUserId : allUsers) {
17864                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
17865                            continue;
17866                        }
17867                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17868                                libEntry.info, 0, currUserId);
17869                        if (!ArrayUtils.isEmpty(libClientPackages)) {
17870                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17871                                    + " hosting lib " + libEntry.info.getName() + " version "
17872                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
17873                                    + " for user " + currUserId);
17874                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17875                        }
17876                    }
17877                }
17878            }
17879
17880            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17881        }
17882
17883        final int freezeUser;
17884        if (isUpdatedSystemApp(uninstalledPs)
17885                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17886            // We're downgrading a system app, which will apply to all users, so
17887            // freeze them all during the downgrade
17888            freezeUser = UserHandle.USER_ALL;
17889        } else {
17890            freezeUser = removeUser;
17891        }
17892
17893        synchronized (mInstallLock) {
17894            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17895            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17896                    deleteFlags, "deletePackageX")) {
17897                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17898                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
17899            }
17900            synchronized (mPackages) {
17901                if (res) {
17902                    if (pkg != null) {
17903                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17904                    }
17905                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
17906                    updateInstantAppInstallerLocked(packageName);
17907                }
17908            }
17909        }
17910
17911        if (res) {
17912            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17913            info.sendPackageRemovedBroadcasts(killApp);
17914            info.sendSystemPackageUpdatedBroadcasts();
17915            info.sendSystemPackageAppearedBroadcasts();
17916        }
17917        // Force a gc here.
17918        Runtime.getRuntime().gc();
17919        // Delete the resources here after sending the broadcast to let
17920        // other processes clean up before deleting resources.
17921        if (info.args != null) {
17922            synchronized (mInstallLock) {
17923                info.args.doPostDeleteLI(true);
17924            }
17925        }
17926
17927        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17928    }
17929
17930    static class PackageRemovedInfo {
17931        final PackageSender packageSender;
17932        String removedPackage;
17933        String installerPackageName;
17934        int uid = -1;
17935        int removedAppId = -1;
17936        int[] origUsers;
17937        int[] removedUsers = null;
17938        int[] broadcastUsers = null;
17939        int[] instantUserIds = null;
17940        SparseArray<Integer> installReasons;
17941        boolean isRemovedPackageSystemUpdate = false;
17942        boolean isUpdate;
17943        boolean dataRemoved;
17944        boolean removedForAllUsers;
17945        boolean isStaticSharedLib;
17946        // Clean up resources deleted packages.
17947        InstallArgs args = null;
17948        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17949        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17950
17951        PackageRemovedInfo(PackageSender packageSender) {
17952            this.packageSender = packageSender;
17953        }
17954
17955        void sendPackageRemovedBroadcasts(boolean killApp) {
17956            sendPackageRemovedBroadcastInternal(killApp);
17957            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17958            for (int i = 0; i < childCount; i++) {
17959                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17960                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17961            }
17962        }
17963
17964        void sendSystemPackageUpdatedBroadcasts() {
17965            if (isRemovedPackageSystemUpdate) {
17966                sendSystemPackageUpdatedBroadcastsInternal();
17967                final int childCount = (removedChildPackages != null)
17968                        ? removedChildPackages.size() : 0;
17969                for (int i = 0; i < childCount; i++) {
17970                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17971                    if (childInfo.isRemovedPackageSystemUpdate) {
17972                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17973                    }
17974                }
17975            }
17976        }
17977
17978        void sendSystemPackageAppearedBroadcasts() {
17979            final int packageCount = (appearedChildPackages != null)
17980                    ? appearedChildPackages.size() : 0;
17981            for (int i = 0; i < packageCount; i++) {
17982                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17983                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
17984                    true /*sendBootCompleted*/, false /*startReceiver*/,
17985                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
17986            }
17987        }
17988
17989        private void sendSystemPackageUpdatedBroadcastsInternal() {
17990            Bundle extras = new Bundle(2);
17991            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17992            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17993            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17994                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
17995            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17996                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
17997            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
17998                null, null, 0, removedPackage, null, null, null);
17999            if (installerPackageName != null) {
18000                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18001                        removedPackage, extras, 0 /*flags*/,
18002                        installerPackageName, null, null, null);
18003                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18004                        removedPackage, extras, 0 /*flags*/,
18005                        installerPackageName, null, null, null);
18006            }
18007        }
18008
18009        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18010            // Don't send static shared library removal broadcasts as these
18011            // libs are visible only the the apps that depend on them an one
18012            // cannot remove the library if it has a dependency.
18013            if (isStaticSharedLib) {
18014                return;
18015            }
18016            Bundle extras = new Bundle(2);
18017            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18018            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18019            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18020            if (isUpdate || isRemovedPackageSystemUpdate) {
18021                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18022            }
18023            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18024            if (removedPackage != null) {
18025                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18026                    removedPackage, extras, 0, null /*targetPackage*/, null,
18027                    broadcastUsers, instantUserIds);
18028                if (installerPackageName != null) {
18029                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18030                            removedPackage, extras, 0 /*flags*/,
18031                            installerPackageName, null, broadcastUsers, instantUserIds);
18032                }
18033                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18034                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18035                        removedPackage, extras,
18036                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18037                        null, null, broadcastUsers, instantUserIds);
18038                    packageSender.notifyPackageRemoved(removedPackage);
18039                }
18040            }
18041            if (removedAppId >= 0) {
18042                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18043                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18044                    null, null, broadcastUsers, instantUserIds);
18045            }
18046        }
18047
18048        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18049            removedUsers = userIds;
18050            if (removedUsers == null) {
18051                broadcastUsers = null;
18052                return;
18053            }
18054
18055            broadcastUsers = EMPTY_INT_ARRAY;
18056            instantUserIds = EMPTY_INT_ARRAY;
18057            for (int i = userIds.length - 1; i >= 0; --i) {
18058                final int userId = userIds[i];
18059                if (deletedPackageSetting.getInstantApp(userId)) {
18060                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
18061                } else {
18062                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18063                }
18064            }
18065        }
18066    }
18067
18068    /*
18069     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18070     * flag is not set, the data directory is removed as well.
18071     * make sure this flag is set for partially installed apps. If not its meaningless to
18072     * delete a partially installed application.
18073     */
18074    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18075            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18076        String packageName = ps.name;
18077        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18078        // Retrieve object to delete permissions for shared user later on
18079        final PackageParser.Package deletedPkg;
18080        final PackageSetting deletedPs;
18081        // reader
18082        synchronized (mPackages) {
18083            deletedPkg = mPackages.get(packageName);
18084            deletedPs = mSettings.mPackages.get(packageName);
18085            if (outInfo != null) {
18086                outInfo.removedPackage = packageName;
18087                outInfo.installerPackageName = ps.installerPackageName;
18088                outInfo.isStaticSharedLib = deletedPkg != null
18089                        && deletedPkg.staticSharedLibName != null;
18090                outInfo.populateUsers(deletedPs == null ? null
18091                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18092            }
18093        }
18094
18095        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
18096
18097        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18098            final PackageParser.Package resolvedPkg;
18099            if (deletedPkg != null) {
18100                resolvedPkg = deletedPkg;
18101            } else {
18102                // We don't have a parsed package when it lives on an ejected
18103                // adopted storage device, so fake something together
18104                resolvedPkg = new PackageParser.Package(ps.name);
18105                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18106            }
18107            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18108                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18109            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18110            if (outInfo != null) {
18111                outInfo.dataRemoved = true;
18112            }
18113            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18114        }
18115
18116        int removedAppId = -1;
18117
18118        // writer
18119        synchronized (mPackages) {
18120            boolean installedStateChanged = false;
18121            if (deletedPs != null) {
18122                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18123                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18124                    clearDefaultBrowserIfNeeded(packageName);
18125                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18126                    removedAppId = mSettings.removePackageLPw(packageName);
18127                    if (outInfo != null) {
18128                        outInfo.removedAppId = removedAppId;
18129                    }
18130                    mPermissionManager.updatePermissions(
18131                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
18132                    if (deletedPs.sharedUser != null) {
18133                        // Remove permissions associated with package. Since runtime
18134                        // permissions are per user we have to kill the removed package
18135                        // or packages running under the shared user of the removed
18136                        // package if revoking the permissions requested only by the removed
18137                        // package is successful and this causes a change in gids.
18138                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18139                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18140                                    userId);
18141                            if (userIdToKill == UserHandle.USER_ALL
18142                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18143                                // If gids changed for this user, kill all affected packages.
18144                                mHandler.post(new Runnable() {
18145                                    @Override
18146                                    public void run() {
18147                                        // This has to happen with no lock held.
18148                                        killApplication(deletedPs.name, deletedPs.appId,
18149                                                KILL_APP_REASON_GIDS_CHANGED);
18150                                    }
18151                                });
18152                                break;
18153                            }
18154                        }
18155                    }
18156                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18157                }
18158                // make sure to preserve per-user disabled state if this removal was just
18159                // a downgrade of a system app to the factory package
18160                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18161                    if (DEBUG_REMOVE) {
18162                        Slog.d(TAG, "Propagating install state across downgrade");
18163                    }
18164                    for (int userId : allUserHandles) {
18165                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18166                        if (DEBUG_REMOVE) {
18167                            Slog.d(TAG, "    user " + userId + " => " + installed);
18168                        }
18169                        if (installed != ps.getInstalled(userId)) {
18170                            installedStateChanged = true;
18171                        }
18172                        ps.setInstalled(installed, userId);
18173                    }
18174                }
18175            }
18176            // can downgrade to reader
18177            if (writeSettings) {
18178                // Save settings now
18179                mSettings.writeLPr();
18180            }
18181            if (installedStateChanged) {
18182                mSettings.writeKernelMappingLPr(ps);
18183            }
18184        }
18185        if (removedAppId != -1) {
18186            // A user ID was deleted here. Go through all users and remove it
18187            // from KeyStore.
18188            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18189        }
18190    }
18191
18192    static boolean locationIsPrivileged(String path) {
18193        try {
18194            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
18195            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
18196            final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
18197            return path.startsWith(privilegedAppDir.getCanonicalPath())
18198                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath())
18199                    || path.startsWith(privilegedProductAppDir.getCanonicalPath());
18200        } catch (IOException e) {
18201            Slog.e(TAG, "Unable to access code path " + path);
18202        }
18203        return false;
18204    }
18205
18206    static boolean locationIsOem(String path) {
18207        try {
18208            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
18209        } catch (IOException e) {
18210            Slog.e(TAG, "Unable to access code path " + path);
18211        }
18212        return false;
18213    }
18214
18215    static boolean locationIsVendor(String path) {
18216        try {
18217            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath());
18218        } catch (IOException e) {
18219            Slog.e(TAG, "Unable to access code path " + path);
18220        }
18221        return false;
18222    }
18223
18224    static boolean locationIsProduct(String path) {
18225        try {
18226            return path.startsWith(Environment.getProductDirectory().getCanonicalPath());
18227        } catch (IOException e) {
18228            Slog.e(TAG, "Unable to access code path " + path);
18229        }
18230        return false;
18231    }
18232
18233    /*
18234     * Tries to delete system package.
18235     */
18236    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18237            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18238            boolean writeSettings) {
18239        if (deletedPs.parentPackageName != null) {
18240            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18241            return false;
18242        }
18243
18244        final boolean applyUserRestrictions
18245                = (allUserHandles != null) && (outInfo.origUsers != null);
18246        final PackageSetting disabledPs;
18247        // Confirm if the system package has been updated
18248        // An updated system app can be deleted. This will also have to restore
18249        // the system pkg from system partition
18250        // reader
18251        synchronized (mPackages) {
18252            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18253        }
18254
18255        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18256                + " disabledPs=" + disabledPs);
18257
18258        if (disabledPs == null) {
18259            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18260            return false;
18261        } else if (DEBUG_REMOVE) {
18262            Slog.d(TAG, "Deleting system pkg from data partition");
18263        }
18264
18265        if (DEBUG_REMOVE) {
18266            if (applyUserRestrictions) {
18267                Slog.d(TAG, "Remembering install states:");
18268                for (int userId : allUserHandles) {
18269                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18270                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18271                }
18272            }
18273        }
18274
18275        // Delete the updated package
18276        outInfo.isRemovedPackageSystemUpdate = true;
18277        if (outInfo.removedChildPackages != null) {
18278            final int childCount = (deletedPs.childPackageNames != null)
18279                    ? deletedPs.childPackageNames.size() : 0;
18280            for (int i = 0; i < childCount; i++) {
18281                String childPackageName = deletedPs.childPackageNames.get(i);
18282                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18283                        .contains(childPackageName)) {
18284                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18285                            childPackageName);
18286                    if (childInfo != null) {
18287                        childInfo.isRemovedPackageSystemUpdate = true;
18288                    }
18289                }
18290            }
18291        }
18292
18293        if (disabledPs.versionCode < deletedPs.versionCode) {
18294            // Delete data for downgrades
18295            flags &= ~PackageManager.DELETE_KEEP_DATA;
18296        } else {
18297            // Preserve data by setting flag
18298            flags |= PackageManager.DELETE_KEEP_DATA;
18299        }
18300
18301        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18302                outInfo, writeSettings, disabledPs.pkg);
18303        if (!ret) {
18304            return false;
18305        }
18306
18307        // writer
18308        synchronized (mPackages) {
18309            // NOTE: The system package always needs to be enabled; even if it's for
18310            // a compressed stub. If we don't, installing the system package fails
18311            // during scan [scanning checks the disabled packages]. We will reverse
18312            // this later, after we've "installed" the stub.
18313            // Reinstate the old system package
18314            enableSystemPackageLPw(disabledPs.pkg);
18315            // Remove any native libraries from the upgraded package.
18316            removeNativeBinariesLI(deletedPs);
18317        }
18318
18319        // Install the system package
18320        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18321        try {
18322            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
18323                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18324        } catch (PackageManagerException e) {
18325            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18326                    + e.getMessage());
18327            return false;
18328        } finally {
18329            if (disabledPs.pkg.isStub) {
18330                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18331            }
18332        }
18333        return true;
18334    }
18335
18336    /**
18337     * Installs a package that's already on the system partition.
18338     */
18339    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
18340            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18341            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18342                    throws PackageManagerException {
18343        @ParseFlags int parseFlags =
18344                mDefParseFlags
18345                | PackageParser.PARSE_MUST_BE_APK
18346                | PackageParser.PARSE_IS_SYSTEM_DIR;
18347        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
18348        if (isPrivileged || locationIsPrivileged(codePathString)) {
18349            scanFlags |= SCAN_AS_PRIVILEGED;
18350        }
18351        if (locationIsOem(codePathString)) {
18352            scanFlags |= SCAN_AS_OEM;
18353        }
18354        if (locationIsVendor(codePathString)) {
18355            scanFlags |= SCAN_AS_VENDOR;
18356        }
18357        if (locationIsProduct(codePathString)) {
18358            scanFlags |= SCAN_AS_PRODUCT;
18359        }
18360
18361        final File codePath = new File(codePathString);
18362        final PackageParser.Package pkg =
18363                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
18364
18365        try {
18366            // update shared libraries for the newly re-installed system package
18367            updateSharedLibrariesLPr(pkg, null);
18368        } catch (PackageManagerException e) {
18369            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18370        }
18371
18372        prepareAppDataAfterInstallLIF(pkg);
18373
18374        // writer
18375        synchronized (mPackages) {
18376            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18377
18378            // Propagate the permissions state as we do not want to drop on the floor
18379            // runtime permissions. The update permissions method below will take
18380            // care of removing obsolete permissions and grant install permissions.
18381            if (origPermissionState != null) {
18382                ps.getPermissionsState().copyFrom(origPermissionState);
18383            }
18384            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18385                    mPermissionCallback);
18386
18387            final boolean applyUserRestrictions
18388                    = (allUserHandles != null) && (origUserHandles != null);
18389            if (applyUserRestrictions) {
18390                boolean installedStateChanged = false;
18391                if (DEBUG_REMOVE) {
18392                    Slog.d(TAG, "Propagating install state across reinstall");
18393                }
18394                for (int userId : allUserHandles) {
18395                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18396                    if (DEBUG_REMOVE) {
18397                        Slog.d(TAG, "    user " + userId + " => " + installed);
18398                    }
18399                    if (installed != ps.getInstalled(userId)) {
18400                        installedStateChanged = true;
18401                    }
18402                    ps.setInstalled(installed, userId);
18403
18404                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18405                }
18406                // Regardless of writeSettings we need to ensure that this restriction
18407                // state propagation is persisted
18408                mSettings.writeAllUsersPackageRestrictionsLPr();
18409                if (installedStateChanged) {
18410                    mSettings.writeKernelMappingLPr(ps);
18411                }
18412            }
18413            // can downgrade to reader here
18414            if (writeSettings) {
18415                mSettings.writeLPr();
18416            }
18417        }
18418        return pkg;
18419    }
18420
18421    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18422            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18423            PackageRemovedInfo outInfo, boolean writeSettings,
18424            PackageParser.Package replacingPackage) {
18425        synchronized (mPackages) {
18426            if (outInfo != null) {
18427                outInfo.uid = ps.appId;
18428            }
18429
18430            if (outInfo != null && outInfo.removedChildPackages != null) {
18431                final int childCount = (ps.childPackageNames != null)
18432                        ? ps.childPackageNames.size() : 0;
18433                for (int i = 0; i < childCount; i++) {
18434                    String childPackageName = ps.childPackageNames.get(i);
18435                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18436                    if (childPs == null) {
18437                        return false;
18438                    }
18439                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18440                            childPackageName);
18441                    if (childInfo != null) {
18442                        childInfo.uid = childPs.appId;
18443                    }
18444                }
18445            }
18446        }
18447
18448        // Delete package data from internal structures and also remove data if flag is set
18449        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18450
18451        // Delete the child packages data
18452        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18453        for (int i = 0; i < childCount; i++) {
18454            PackageSetting childPs;
18455            synchronized (mPackages) {
18456                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18457            }
18458            if (childPs != null) {
18459                PackageRemovedInfo childOutInfo = (outInfo != null
18460                        && outInfo.removedChildPackages != null)
18461                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18462                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18463                        && (replacingPackage != null
18464                        && !replacingPackage.hasChildPackage(childPs.name))
18465                        ? flags & ~DELETE_KEEP_DATA : flags;
18466                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18467                        deleteFlags, writeSettings);
18468            }
18469        }
18470
18471        // Delete application code and resources only for parent packages
18472        if (ps.parentPackageName == null) {
18473            if (deleteCodeAndResources && (outInfo != null)) {
18474                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18475                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18476                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18477            }
18478        }
18479
18480        return true;
18481    }
18482
18483    @Override
18484    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18485            int userId) {
18486        mContext.enforceCallingOrSelfPermission(
18487                android.Manifest.permission.DELETE_PACKAGES, null);
18488        synchronized (mPackages) {
18489            // Cannot block uninstall of static shared libs as they are
18490            // considered a part of the using app (emulating static linking).
18491            // Also static libs are installed always on internal storage.
18492            PackageParser.Package pkg = mPackages.get(packageName);
18493            if (pkg != null && pkg.staticSharedLibName != null) {
18494                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18495                        + " providing static shared library: " + pkg.staticSharedLibName);
18496                return false;
18497            }
18498            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18499            mSettings.writePackageRestrictionsLPr(userId);
18500        }
18501        return true;
18502    }
18503
18504    @Override
18505    public boolean getBlockUninstallForUser(String packageName, int userId) {
18506        synchronized (mPackages) {
18507            final PackageSetting ps = mSettings.mPackages.get(packageName);
18508            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18509                return false;
18510            }
18511            return mSettings.getBlockUninstallLPr(userId, packageName);
18512        }
18513    }
18514
18515    @Override
18516    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18517        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18518        synchronized (mPackages) {
18519            PackageSetting ps = mSettings.mPackages.get(packageName);
18520            if (ps == null) {
18521                Log.w(TAG, "Package doesn't exist: " + packageName);
18522                return false;
18523            }
18524            if (systemUserApp) {
18525                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18526            } else {
18527                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18528            }
18529            mSettings.writeLPr();
18530        }
18531        return true;
18532    }
18533
18534    /*
18535     * This method handles package deletion in general
18536     */
18537    private boolean deletePackageLIF(String packageName, UserHandle user,
18538            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18539            PackageRemovedInfo outInfo, boolean writeSettings,
18540            PackageParser.Package replacingPackage) {
18541        if (packageName == null) {
18542            Slog.w(TAG, "Attempt to delete null packageName.");
18543            return false;
18544        }
18545
18546        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18547
18548        PackageSetting ps;
18549        synchronized (mPackages) {
18550            ps = mSettings.mPackages.get(packageName);
18551            if (ps == null) {
18552                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18553                return false;
18554            }
18555
18556            if (ps.parentPackageName != null && (!isSystemApp(ps)
18557                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18558                if (DEBUG_REMOVE) {
18559                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18560                            + ((user == null) ? UserHandle.USER_ALL : user));
18561                }
18562                final int removedUserId = (user != null) ? user.getIdentifier()
18563                        : UserHandle.USER_ALL;
18564                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18565                    return false;
18566                }
18567                markPackageUninstalledForUserLPw(ps, user);
18568                scheduleWritePackageRestrictionsLocked(user);
18569                return true;
18570            }
18571        }
18572
18573        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18574                && user.getIdentifier() != UserHandle.USER_ALL)) {
18575            // The caller is asking that the package only be deleted for a single
18576            // user.  To do this, we just mark its uninstalled state and delete
18577            // its data. If this is a system app, we only allow this to happen if
18578            // they have set the special DELETE_SYSTEM_APP which requests different
18579            // semantics than normal for uninstalling system apps.
18580            markPackageUninstalledForUserLPw(ps, user);
18581
18582            if (!isSystemApp(ps)) {
18583                // Do not uninstall the APK if an app should be cached
18584                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18585                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18586                    // Other user still have this package installed, so all
18587                    // we need to do is clear this user's data and save that
18588                    // it is uninstalled.
18589                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18590                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18591                        return false;
18592                    }
18593                    scheduleWritePackageRestrictionsLocked(user);
18594                    return true;
18595                } else {
18596                    // We need to set it back to 'installed' so the uninstall
18597                    // broadcasts will be sent correctly.
18598                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18599                    ps.setInstalled(true, user.getIdentifier());
18600                    mSettings.writeKernelMappingLPr(ps);
18601                }
18602            } else {
18603                // This is a system app, so we assume that the
18604                // other users still have this package installed, so all
18605                // we need to do is clear this user's data and save that
18606                // it is uninstalled.
18607                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18608                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18609                    return false;
18610                }
18611                scheduleWritePackageRestrictionsLocked(user);
18612                return true;
18613            }
18614        }
18615
18616        // If we are deleting a composite package for all users, keep track
18617        // of result for each child.
18618        if (ps.childPackageNames != null && outInfo != null) {
18619            synchronized (mPackages) {
18620                final int childCount = ps.childPackageNames.size();
18621                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18622                for (int i = 0; i < childCount; i++) {
18623                    String childPackageName = ps.childPackageNames.get(i);
18624                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18625                    childInfo.removedPackage = childPackageName;
18626                    childInfo.installerPackageName = ps.installerPackageName;
18627                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18628                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18629                    if (childPs != null) {
18630                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18631                    }
18632                }
18633            }
18634        }
18635
18636        boolean ret = false;
18637        if (isSystemApp(ps)) {
18638            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18639            // When an updated system application is deleted we delete the existing resources
18640            // as well and fall back to existing code in system partition
18641            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18642        } else {
18643            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18644            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18645                    outInfo, writeSettings, replacingPackage);
18646        }
18647
18648        // Take a note whether we deleted the package for all users
18649        if (outInfo != null) {
18650            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18651            if (outInfo.removedChildPackages != null) {
18652                synchronized (mPackages) {
18653                    final int childCount = outInfo.removedChildPackages.size();
18654                    for (int i = 0; i < childCount; i++) {
18655                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18656                        if (childInfo != null) {
18657                            childInfo.removedForAllUsers = mPackages.get(
18658                                    childInfo.removedPackage) == null;
18659                        }
18660                    }
18661                }
18662            }
18663            // If we uninstalled an update to a system app there may be some
18664            // child packages that appeared as they are declared in the system
18665            // app but were not declared in the update.
18666            if (isSystemApp(ps)) {
18667                synchronized (mPackages) {
18668                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18669                    final int childCount = (updatedPs.childPackageNames != null)
18670                            ? updatedPs.childPackageNames.size() : 0;
18671                    for (int i = 0; i < childCount; i++) {
18672                        String childPackageName = updatedPs.childPackageNames.get(i);
18673                        if (outInfo.removedChildPackages == null
18674                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18675                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18676                            if (childPs == null) {
18677                                continue;
18678                            }
18679                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18680                            installRes.name = childPackageName;
18681                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18682                            installRes.pkg = mPackages.get(childPackageName);
18683                            installRes.uid = childPs.pkg.applicationInfo.uid;
18684                            if (outInfo.appearedChildPackages == null) {
18685                                outInfo.appearedChildPackages = new ArrayMap<>();
18686                            }
18687                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18688                        }
18689                    }
18690                }
18691            }
18692        }
18693
18694        return ret;
18695    }
18696
18697    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18698        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18699                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18700        for (int nextUserId : userIds) {
18701            if (DEBUG_REMOVE) {
18702                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18703            }
18704            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18705                    false /*installed*/,
18706                    true /*stopped*/,
18707                    true /*notLaunched*/,
18708                    false /*hidden*/,
18709                    false /*suspended*/,
18710                    false /*instantApp*/,
18711                    false /*virtualPreload*/,
18712                    null /*lastDisableAppCaller*/,
18713                    null /*enabledComponents*/,
18714                    null /*disabledComponents*/,
18715                    ps.readUserState(nextUserId).domainVerificationStatus,
18716                    0, PackageManager.INSTALL_REASON_UNKNOWN,
18717                    null /*harmfulAppWarning*/);
18718        }
18719        mSettings.writeKernelMappingLPr(ps);
18720    }
18721
18722    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18723            PackageRemovedInfo outInfo) {
18724        final PackageParser.Package pkg;
18725        synchronized (mPackages) {
18726            pkg = mPackages.get(ps.name);
18727        }
18728
18729        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18730                : new int[] {userId};
18731        for (int nextUserId : userIds) {
18732            if (DEBUG_REMOVE) {
18733                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18734                        + nextUserId);
18735            }
18736
18737            destroyAppDataLIF(pkg, userId,
18738                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18739            destroyAppProfilesLIF(pkg, userId);
18740            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18741            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18742            schedulePackageCleaning(ps.name, nextUserId, false);
18743            synchronized (mPackages) {
18744                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18745                    scheduleWritePackageRestrictionsLocked(nextUserId);
18746                }
18747                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18748            }
18749        }
18750
18751        if (outInfo != null) {
18752            outInfo.removedPackage = ps.name;
18753            outInfo.installerPackageName = ps.installerPackageName;
18754            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18755            outInfo.removedAppId = ps.appId;
18756            outInfo.removedUsers = userIds;
18757            outInfo.broadcastUsers = userIds;
18758        }
18759
18760        return true;
18761    }
18762
18763    private final class ClearStorageConnection implements ServiceConnection {
18764        IMediaContainerService mContainerService;
18765
18766        @Override
18767        public void onServiceConnected(ComponentName name, IBinder service) {
18768            synchronized (this) {
18769                mContainerService = IMediaContainerService.Stub
18770                        .asInterface(Binder.allowBlocking(service));
18771                notifyAll();
18772            }
18773        }
18774
18775        @Override
18776        public void onServiceDisconnected(ComponentName name) {
18777        }
18778    }
18779
18780    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18781        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18782
18783        final boolean mounted;
18784        if (Environment.isExternalStorageEmulated()) {
18785            mounted = true;
18786        } else {
18787            final String status = Environment.getExternalStorageState();
18788
18789            mounted = status.equals(Environment.MEDIA_MOUNTED)
18790                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18791        }
18792
18793        if (!mounted) {
18794            return;
18795        }
18796
18797        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18798        int[] users;
18799        if (userId == UserHandle.USER_ALL) {
18800            users = sUserManager.getUserIds();
18801        } else {
18802            users = new int[] { userId };
18803        }
18804        final ClearStorageConnection conn = new ClearStorageConnection();
18805        if (mContext.bindServiceAsUser(
18806                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18807            try {
18808                for (int curUser : users) {
18809                    long timeout = SystemClock.uptimeMillis() + 5000;
18810                    synchronized (conn) {
18811                        long now;
18812                        while (conn.mContainerService == null &&
18813                                (now = SystemClock.uptimeMillis()) < timeout) {
18814                            try {
18815                                conn.wait(timeout - now);
18816                            } catch (InterruptedException e) {
18817                            }
18818                        }
18819                    }
18820                    if (conn.mContainerService == null) {
18821                        return;
18822                    }
18823
18824                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18825                    clearDirectory(conn.mContainerService,
18826                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18827                    if (allData) {
18828                        clearDirectory(conn.mContainerService,
18829                                userEnv.buildExternalStorageAppDataDirs(packageName));
18830                        clearDirectory(conn.mContainerService,
18831                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18832                    }
18833                }
18834            } finally {
18835                mContext.unbindService(conn);
18836            }
18837        }
18838    }
18839
18840    @Override
18841    public void clearApplicationProfileData(String packageName) {
18842        enforceSystemOrRoot("Only the system can clear all profile data");
18843
18844        final PackageParser.Package pkg;
18845        synchronized (mPackages) {
18846            pkg = mPackages.get(packageName);
18847        }
18848
18849        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18850            synchronized (mInstallLock) {
18851                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18852            }
18853        }
18854    }
18855
18856    @Override
18857    public void clearApplicationUserData(final String packageName,
18858            final IPackageDataObserver observer, final int userId) {
18859        mContext.enforceCallingOrSelfPermission(
18860                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18861
18862        final int callingUid = Binder.getCallingUid();
18863        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18864                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18865
18866        final PackageSetting ps = mSettings.getPackageLPr(packageName);
18867        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
18868        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18869            throw new SecurityException("Cannot clear data for a protected package: "
18870                    + packageName);
18871        }
18872        // Queue up an async operation since the package deletion may take a little while.
18873        mHandler.post(new Runnable() {
18874            public void run() {
18875                mHandler.removeCallbacks(this);
18876                final boolean succeeded;
18877                if (!filterApp) {
18878                    try (PackageFreezer freezer = freezePackage(packageName,
18879                            "clearApplicationUserData")) {
18880                        synchronized (mInstallLock) {
18881                            succeeded = clearApplicationUserDataLIF(packageName, userId);
18882                        }
18883                        clearExternalStorageDataSync(packageName, userId, true);
18884                        synchronized (mPackages) {
18885                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18886                                    packageName, userId);
18887                        }
18888                    }
18889                    if (succeeded) {
18890                        // invoke DeviceStorageMonitor's update method to clear any notifications
18891                        DeviceStorageMonitorInternal dsm = LocalServices
18892                                .getService(DeviceStorageMonitorInternal.class);
18893                        if (dsm != null) {
18894                            dsm.checkMemory();
18895                        }
18896                    }
18897                } else {
18898                    succeeded = false;
18899                }
18900                if (observer != null) {
18901                    try {
18902                        observer.onRemoveCompleted(packageName, succeeded);
18903                    } catch (RemoteException e) {
18904                        Log.i(TAG, "Observer no longer exists.");
18905                    }
18906                } //end if observer
18907            } //end run
18908        });
18909    }
18910
18911    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18912        if (packageName == null) {
18913            Slog.w(TAG, "Attempt to delete null packageName.");
18914            return false;
18915        }
18916
18917        // Try finding details about the requested package
18918        PackageParser.Package pkg;
18919        synchronized (mPackages) {
18920            pkg = mPackages.get(packageName);
18921            if (pkg == null) {
18922                final PackageSetting ps = mSettings.mPackages.get(packageName);
18923                if (ps != null) {
18924                    pkg = ps.pkg;
18925                }
18926            }
18927
18928            if (pkg == null) {
18929                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18930                return false;
18931            }
18932
18933            PackageSetting ps = (PackageSetting) pkg.mExtras;
18934            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18935        }
18936
18937        clearAppDataLIF(pkg, userId,
18938                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18939
18940        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18941        removeKeystoreDataIfNeeded(userId, appId);
18942
18943        UserManagerInternal umInternal = getUserManagerInternal();
18944        final int flags;
18945        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18946            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18947        } else if (umInternal.isUserRunning(userId)) {
18948            flags = StorageManager.FLAG_STORAGE_DE;
18949        } else {
18950            flags = 0;
18951        }
18952        prepareAppDataContentsLIF(pkg, userId, flags);
18953
18954        return true;
18955    }
18956
18957    /**
18958     * Reverts user permission state changes (permissions and flags) in
18959     * all packages for a given user.
18960     *
18961     * @param userId The device user for which to do a reset.
18962     */
18963    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18964        final int packageCount = mPackages.size();
18965        for (int i = 0; i < packageCount; i++) {
18966            PackageParser.Package pkg = mPackages.valueAt(i);
18967            PackageSetting ps = (PackageSetting) pkg.mExtras;
18968            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18969        }
18970    }
18971
18972    private void resetNetworkPolicies(int userId) {
18973        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18974    }
18975
18976    /**
18977     * Reverts user permission state changes (permissions and flags).
18978     *
18979     * @param ps The package for which to reset.
18980     * @param userId The device user for which to do a reset.
18981     */
18982    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18983            final PackageSetting ps, final int userId) {
18984        if (ps.pkg == null) {
18985            return;
18986        }
18987
18988        // These are flags that can change base on user actions.
18989        final int userSettableMask = FLAG_PERMISSION_USER_SET
18990                | FLAG_PERMISSION_USER_FIXED
18991                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18992                | FLAG_PERMISSION_REVIEW_REQUIRED;
18993
18994        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18995                | FLAG_PERMISSION_POLICY_FIXED;
18996
18997        boolean writeInstallPermissions = false;
18998        boolean writeRuntimePermissions = false;
18999
19000        final int permissionCount = ps.pkg.requestedPermissions.size();
19001        for (int i = 0; i < permissionCount; i++) {
19002            final String permName = ps.pkg.requestedPermissions.get(i);
19003            final BasePermission bp =
19004                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19005            if (bp == null) {
19006                continue;
19007            }
19008
19009            // If shared user we just reset the state to which only this app contributed.
19010            if (ps.sharedUser != null) {
19011                boolean used = false;
19012                final int packageCount = ps.sharedUser.packages.size();
19013                for (int j = 0; j < packageCount; j++) {
19014                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19015                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19016                            && pkg.pkg.requestedPermissions.contains(permName)) {
19017                        used = true;
19018                        break;
19019                    }
19020                }
19021                if (used) {
19022                    continue;
19023                }
19024            }
19025
19026            final PermissionsState permissionsState = ps.getPermissionsState();
19027
19028            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19029
19030            // Always clear the user settable flags.
19031            final boolean hasInstallState =
19032                    permissionsState.getInstallPermissionState(permName) != null;
19033            // If permission review is enabled and this is a legacy app, mark the
19034            // permission as requiring a review as this is the initial state.
19035            int flags = 0;
19036            if (mSettings.mPermissions.mPermissionReviewRequired
19037                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19038                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19039            }
19040            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19041                if (hasInstallState) {
19042                    writeInstallPermissions = true;
19043                } else {
19044                    writeRuntimePermissions = true;
19045                }
19046            }
19047
19048            // Below is only runtime permission handling.
19049            if (!bp.isRuntime()) {
19050                continue;
19051            }
19052
19053            // Never clobber system or policy.
19054            if ((oldFlags & policyOrSystemFlags) != 0) {
19055                continue;
19056            }
19057
19058            // If this permission was granted by default, make sure it is.
19059            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19060                if (permissionsState.grantRuntimePermission(bp, userId)
19061                        != PERMISSION_OPERATION_FAILURE) {
19062                    writeRuntimePermissions = true;
19063                }
19064            // If permission review is enabled the permissions for a legacy apps
19065            // are represented as constantly granted runtime ones, so don't revoke.
19066            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19067                // Otherwise, reset the permission.
19068                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19069                switch (revokeResult) {
19070                    case PERMISSION_OPERATION_SUCCESS:
19071                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19072                        writeRuntimePermissions = true;
19073                        final int appId = ps.appId;
19074                        mHandler.post(new Runnable() {
19075                            @Override
19076                            public void run() {
19077                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19078                            }
19079                        });
19080                    } break;
19081                }
19082            }
19083        }
19084
19085        // Synchronously write as we are taking permissions away.
19086        if (writeRuntimePermissions) {
19087            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19088        }
19089
19090        // Synchronously write as we are taking permissions away.
19091        if (writeInstallPermissions) {
19092            mSettings.writeLPr();
19093        }
19094    }
19095
19096    /**
19097     * Remove entries from the keystore daemon. Will only remove it if the
19098     * {@code appId} is valid.
19099     */
19100    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19101        if (appId < 0) {
19102            return;
19103        }
19104
19105        final KeyStore keyStore = KeyStore.getInstance();
19106        if (keyStore != null) {
19107            if (userId == UserHandle.USER_ALL) {
19108                for (final int individual : sUserManager.getUserIds()) {
19109                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19110                }
19111            } else {
19112                keyStore.clearUid(UserHandle.getUid(userId, appId));
19113            }
19114        } else {
19115            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19116        }
19117    }
19118
19119    @Override
19120    public void deleteApplicationCacheFiles(final String packageName,
19121            final IPackageDataObserver observer) {
19122        final int userId = UserHandle.getCallingUserId();
19123        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19124    }
19125
19126    @Override
19127    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19128            final IPackageDataObserver observer) {
19129        final int callingUid = Binder.getCallingUid();
19130        mContext.enforceCallingOrSelfPermission(
19131                android.Manifest.permission.DELETE_CACHE_FILES, null);
19132        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19133                /* requireFullPermission= */ true, /* checkShell= */ false,
19134                "delete application cache files");
19135        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19136                android.Manifest.permission.ACCESS_INSTANT_APPS);
19137
19138        final PackageParser.Package pkg;
19139        synchronized (mPackages) {
19140            pkg = mPackages.get(packageName);
19141        }
19142
19143        // Queue up an async operation since the package deletion may take a little while.
19144        mHandler.post(new Runnable() {
19145            public void run() {
19146                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19147                boolean doClearData = true;
19148                if (ps != null) {
19149                    final boolean targetIsInstantApp =
19150                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19151                    doClearData = !targetIsInstantApp
19152                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19153                }
19154                if (doClearData) {
19155                    synchronized (mInstallLock) {
19156                        final int flags = StorageManager.FLAG_STORAGE_DE
19157                                | StorageManager.FLAG_STORAGE_CE;
19158                        // We're only clearing cache files, so we don't care if the
19159                        // app is unfrozen and still able to run
19160                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19161                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19162                    }
19163                    clearExternalStorageDataSync(packageName, userId, false);
19164                }
19165                if (observer != null) {
19166                    try {
19167                        observer.onRemoveCompleted(packageName, true);
19168                    } catch (RemoteException e) {
19169                        Log.i(TAG, "Observer no longer exists.");
19170                    }
19171                }
19172            }
19173        });
19174    }
19175
19176    @Override
19177    public void getPackageSizeInfo(final String packageName, int userHandle,
19178            final IPackageStatsObserver observer) {
19179        throw new UnsupportedOperationException(
19180                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19181    }
19182
19183    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19184        final PackageSetting ps;
19185        synchronized (mPackages) {
19186            ps = mSettings.mPackages.get(packageName);
19187            if (ps == null) {
19188                Slog.w(TAG, "Failed to find settings for " + packageName);
19189                return false;
19190            }
19191        }
19192
19193        final String[] packageNames = { packageName };
19194        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19195        final String[] codePaths = { ps.codePathString };
19196
19197        try {
19198            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19199                    ps.appId, ceDataInodes, codePaths, stats);
19200
19201            // For now, ignore code size of packages on system partition
19202            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19203                stats.codeSize = 0;
19204            }
19205
19206            // External clients expect these to be tracked separately
19207            stats.dataSize -= stats.cacheSize;
19208
19209        } catch (InstallerException e) {
19210            Slog.w(TAG, String.valueOf(e));
19211            return false;
19212        }
19213
19214        return true;
19215    }
19216
19217    private int getUidTargetSdkVersionLockedLPr(int uid) {
19218        Object obj = mSettings.getUserIdLPr(uid);
19219        if (obj instanceof SharedUserSetting) {
19220            final SharedUserSetting sus = (SharedUserSetting) obj;
19221            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19222            final Iterator<PackageSetting> it = sus.packages.iterator();
19223            while (it.hasNext()) {
19224                final PackageSetting ps = it.next();
19225                if (ps.pkg != null) {
19226                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19227                    if (v < vers) vers = v;
19228                }
19229            }
19230            return vers;
19231        } else if (obj instanceof PackageSetting) {
19232            final PackageSetting ps = (PackageSetting) obj;
19233            if (ps.pkg != null) {
19234                return ps.pkg.applicationInfo.targetSdkVersion;
19235            }
19236        }
19237        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19238    }
19239
19240    private int getPackageTargetSdkVersionLockedLPr(String packageName) {
19241        final PackageParser.Package p = mPackages.get(packageName);
19242        if (p != null) {
19243            return p.applicationInfo.targetSdkVersion;
19244        }
19245        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19246    }
19247
19248    @Override
19249    public void addPreferredActivity(IntentFilter filter, int match,
19250            ComponentName[] set, ComponentName activity, int userId) {
19251        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19252                "Adding preferred");
19253    }
19254
19255    private void addPreferredActivityInternal(IntentFilter filter, int match,
19256            ComponentName[] set, ComponentName activity, boolean always, int userId,
19257            String opname) {
19258        // writer
19259        int callingUid = Binder.getCallingUid();
19260        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19261                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19262        if (filter.countActions() == 0) {
19263            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19264            return;
19265        }
19266        synchronized (mPackages) {
19267            if (mContext.checkCallingOrSelfPermission(
19268                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19269                    != PackageManager.PERMISSION_GRANTED) {
19270                if (getUidTargetSdkVersionLockedLPr(callingUid)
19271                        < Build.VERSION_CODES.FROYO) {
19272                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19273                            + callingUid);
19274                    return;
19275                }
19276                mContext.enforceCallingOrSelfPermission(
19277                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19278            }
19279
19280            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19281            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19282                    + userId + ":");
19283            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19284            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19285            scheduleWritePackageRestrictionsLocked(userId);
19286            postPreferredActivityChangedBroadcast(userId);
19287        }
19288    }
19289
19290    private void postPreferredActivityChangedBroadcast(int userId) {
19291        mHandler.post(() -> {
19292            final IActivityManager am = ActivityManager.getService();
19293            if (am == null) {
19294                return;
19295            }
19296
19297            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19298            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19299            try {
19300                am.broadcastIntent(null, intent, null, null,
19301                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19302                        null, false, false, userId);
19303            } catch (RemoteException e) {
19304            }
19305        });
19306    }
19307
19308    @Override
19309    public void replacePreferredActivity(IntentFilter filter, int match,
19310            ComponentName[] set, ComponentName activity, int userId) {
19311        if (filter.countActions() != 1) {
19312            throw new IllegalArgumentException(
19313                    "replacePreferredActivity expects filter to have only 1 action.");
19314        }
19315        if (filter.countDataAuthorities() != 0
19316                || filter.countDataPaths() != 0
19317                || filter.countDataSchemes() > 1
19318                || filter.countDataTypes() != 0) {
19319            throw new IllegalArgumentException(
19320                    "replacePreferredActivity expects filter to have no data authorities, " +
19321                    "paths, or types; and at most one scheme.");
19322        }
19323
19324        final int callingUid = Binder.getCallingUid();
19325        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19326                true /* requireFullPermission */, false /* checkShell */,
19327                "replace preferred activity");
19328        synchronized (mPackages) {
19329            if (mContext.checkCallingOrSelfPermission(
19330                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19331                    != PackageManager.PERMISSION_GRANTED) {
19332                if (getUidTargetSdkVersionLockedLPr(callingUid)
19333                        < Build.VERSION_CODES.FROYO) {
19334                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19335                            + Binder.getCallingUid());
19336                    return;
19337                }
19338                mContext.enforceCallingOrSelfPermission(
19339                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19340            }
19341
19342            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19343            if (pir != null) {
19344                // Get all of the existing entries that exactly match this filter.
19345                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19346                if (existing != null && existing.size() == 1) {
19347                    PreferredActivity cur = existing.get(0);
19348                    if (DEBUG_PREFERRED) {
19349                        Slog.i(TAG, "Checking replace of preferred:");
19350                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19351                        if (!cur.mPref.mAlways) {
19352                            Slog.i(TAG, "  -- CUR; not mAlways!");
19353                        } else {
19354                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19355                            Slog.i(TAG, "  -- CUR: mSet="
19356                                    + Arrays.toString(cur.mPref.mSetComponents));
19357                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19358                            Slog.i(TAG, "  -- NEW: mMatch="
19359                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19360                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19361                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19362                        }
19363                    }
19364                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19365                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19366                            && cur.mPref.sameSet(set)) {
19367                        // Setting the preferred activity to what it happens to be already
19368                        if (DEBUG_PREFERRED) {
19369                            Slog.i(TAG, "Replacing with same preferred activity "
19370                                    + cur.mPref.mShortComponent + " for user "
19371                                    + userId + ":");
19372                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19373                        }
19374                        return;
19375                    }
19376                }
19377
19378                if (existing != null) {
19379                    if (DEBUG_PREFERRED) {
19380                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19381                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19382                    }
19383                    for (int i = 0; i < existing.size(); i++) {
19384                        PreferredActivity pa = existing.get(i);
19385                        if (DEBUG_PREFERRED) {
19386                            Slog.i(TAG, "Removing existing preferred activity "
19387                                    + pa.mPref.mComponent + ":");
19388                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19389                        }
19390                        pir.removeFilter(pa);
19391                    }
19392                }
19393            }
19394            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19395                    "Replacing preferred");
19396        }
19397    }
19398
19399    @Override
19400    public void clearPackagePreferredActivities(String packageName) {
19401        final int callingUid = Binder.getCallingUid();
19402        if (getInstantAppPackageName(callingUid) != null) {
19403            return;
19404        }
19405        // writer
19406        synchronized (mPackages) {
19407            PackageParser.Package pkg = mPackages.get(packageName);
19408            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19409                if (mContext.checkCallingOrSelfPermission(
19410                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19411                        != PackageManager.PERMISSION_GRANTED) {
19412                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19413                            < Build.VERSION_CODES.FROYO) {
19414                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19415                                + callingUid);
19416                        return;
19417                    }
19418                    mContext.enforceCallingOrSelfPermission(
19419                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19420                }
19421            }
19422            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19423            if (ps != null
19424                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19425                return;
19426            }
19427            int user = UserHandle.getCallingUserId();
19428            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19429                scheduleWritePackageRestrictionsLocked(user);
19430            }
19431        }
19432    }
19433
19434    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19435    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19436        ArrayList<PreferredActivity> removed = null;
19437        boolean changed = false;
19438        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19439            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19440            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19441            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19442                continue;
19443            }
19444            Iterator<PreferredActivity> it = pir.filterIterator();
19445            while (it.hasNext()) {
19446                PreferredActivity pa = it.next();
19447                // Mark entry for removal only if it matches the package name
19448                // and the entry is of type "always".
19449                if (packageName == null ||
19450                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19451                                && pa.mPref.mAlways)) {
19452                    if (removed == null) {
19453                        removed = new ArrayList<PreferredActivity>();
19454                    }
19455                    removed.add(pa);
19456                }
19457            }
19458            if (removed != null) {
19459                for (int j=0; j<removed.size(); j++) {
19460                    PreferredActivity pa = removed.get(j);
19461                    pir.removeFilter(pa);
19462                }
19463                changed = true;
19464            }
19465        }
19466        if (changed) {
19467            postPreferredActivityChangedBroadcast(userId);
19468        }
19469        return changed;
19470    }
19471
19472    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19473    private void clearIntentFilterVerificationsLPw(int userId) {
19474        final int packageCount = mPackages.size();
19475        for (int i = 0; i < packageCount; i++) {
19476            PackageParser.Package pkg = mPackages.valueAt(i);
19477            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19478        }
19479    }
19480
19481    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19482    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19483        if (userId == UserHandle.USER_ALL) {
19484            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19485                    sUserManager.getUserIds())) {
19486                for (int oneUserId : sUserManager.getUserIds()) {
19487                    scheduleWritePackageRestrictionsLocked(oneUserId);
19488                }
19489            }
19490        } else {
19491            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19492                scheduleWritePackageRestrictionsLocked(userId);
19493            }
19494        }
19495    }
19496
19497    /** Clears state for all users, and touches intent filter verification policy */
19498    void clearDefaultBrowserIfNeeded(String packageName) {
19499        for (int oneUserId : sUserManager.getUserIds()) {
19500            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19501        }
19502    }
19503
19504    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19505        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19506        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19507            if (packageName.equals(defaultBrowserPackageName)) {
19508                setDefaultBrowserPackageName(null, userId);
19509            }
19510        }
19511    }
19512
19513    @Override
19514    public void resetApplicationPreferences(int userId) {
19515        mContext.enforceCallingOrSelfPermission(
19516                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19517        final long identity = Binder.clearCallingIdentity();
19518        // writer
19519        try {
19520            synchronized (mPackages) {
19521                clearPackagePreferredActivitiesLPw(null, userId);
19522                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19523                // TODO: We have to reset the default SMS and Phone. This requires
19524                // significant refactoring to keep all default apps in the package
19525                // manager (cleaner but more work) or have the services provide
19526                // callbacks to the package manager to request a default app reset.
19527                applyFactoryDefaultBrowserLPw(userId);
19528                clearIntentFilterVerificationsLPw(userId);
19529                primeDomainVerificationsLPw(userId);
19530                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19531                scheduleWritePackageRestrictionsLocked(userId);
19532            }
19533            resetNetworkPolicies(userId);
19534        } finally {
19535            Binder.restoreCallingIdentity(identity);
19536        }
19537    }
19538
19539    @Override
19540    public int getPreferredActivities(List<IntentFilter> outFilters,
19541            List<ComponentName> outActivities, String packageName) {
19542        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19543            return 0;
19544        }
19545        int num = 0;
19546        final int userId = UserHandle.getCallingUserId();
19547        // reader
19548        synchronized (mPackages) {
19549            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19550            if (pir != null) {
19551                final Iterator<PreferredActivity> it = pir.filterIterator();
19552                while (it.hasNext()) {
19553                    final PreferredActivity pa = it.next();
19554                    if (packageName == null
19555                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19556                                    && pa.mPref.mAlways)) {
19557                        if (outFilters != null) {
19558                            outFilters.add(new IntentFilter(pa));
19559                        }
19560                        if (outActivities != null) {
19561                            outActivities.add(pa.mPref.mComponent);
19562                        }
19563                    }
19564                }
19565            }
19566        }
19567
19568        return num;
19569    }
19570
19571    @Override
19572    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19573            int userId) {
19574        int callingUid = Binder.getCallingUid();
19575        if (callingUid != Process.SYSTEM_UID) {
19576            throw new SecurityException(
19577                    "addPersistentPreferredActivity can only be run by the system");
19578        }
19579        if (filter.countActions() == 0) {
19580            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19581            return;
19582        }
19583        synchronized (mPackages) {
19584            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19585                    ":");
19586            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19587            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19588                    new PersistentPreferredActivity(filter, activity));
19589            scheduleWritePackageRestrictionsLocked(userId);
19590            postPreferredActivityChangedBroadcast(userId);
19591        }
19592    }
19593
19594    @Override
19595    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19596        int callingUid = Binder.getCallingUid();
19597        if (callingUid != Process.SYSTEM_UID) {
19598            throw new SecurityException(
19599                    "clearPackagePersistentPreferredActivities can only be run by the system");
19600        }
19601        ArrayList<PersistentPreferredActivity> removed = null;
19602        boolean changed = false;
19603        synchronized (mPackages) {
19604            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19605                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19606                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19607                        .valueAt(i);
19608                if (userId != thisUserId) {
19609                    continue;
19610                }
19611                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19612                while (it.hasNext()) {
19613                    PersistentPreferredActivity ppa = it.next();
19614                    // Mark entry for removal only if it matches the package name.
19615                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19616                        if (removed == null) {
19617                            removed = new ArrayList<PersistentPreferredActivity>();
19618                        }
19619                        removed.add(ppa);
19620                    }
19621                }
19622                if (removed != null) {
19623                    for (int j=0; j<removed.size(); j++) {
19624                        PersistentPreferredActivity ppa = removed.get(j);
19625                        ppir.removeFilter(ppa);
19626                    }
19627                    changed = true;
19628                }
19629            }
19630
19631            if (changed) {
19632                scheduleWritePackageRestrictionsLocked(userId);
19633                postPreferredActivityChangedBroadcast(userId);
19634            }
19635        }
19636    }
19637
19638    /**
19639     * Common machinery for picking apart a restored XML blob and passing
19640     * it to a caller-supplied functor to be applied to the running system.
19641     */
19642    private void restoreFromXml(XmlPullParser parser, int userId,
19643            String expectedStartTag, BlobXmlRestorer functor)
19644            throws IOException, XmlPullParserException {
19645        int type;
19646        while ((type = parser.next()) != XmlPullParser.START_TAG
19647                && type != XmlPullParser.END_DOCUMENT) {
19648        }
19649        if (type != XmlPullParser.START_TAG) {
19650            // oops didn't find a start tag?!
19651            if (DEBUG_BACKUP) {
19652                Slog.e(TAG, "Didn't find start tag during restore");
19653            }
19654            return;
19655        }
19656Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19657        // this is supposed to be TAG_PREFERRED_BACKUP
19658        if (!expectedStartTag.equals(parser.getName())) {
19659            if (DEBUG_BACKUP) {
19660                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19661            }
19662            return;
19663        }
19664
19665        // skip interfering stuff, then we're aligned with the backing implementation
19666        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19667Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19668        functor.apply(parser, userId);
19669    }
19670
19671    private interface BlobXmlRestorer {
19672        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19673    }
19674
19675    /**
19676     * Non-Binder method, support for the backup/restore mechanism: write the
19677     * full set of preferred activities in its canonical XML format.  Returns the
19678     * XML output as a byte array, or null if there is none.
19679     */
19680    @Override
19681    public byte[] getPreferredActivityBackup(int userId) {
19682        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19683            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19684        }
19685
19686        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19687        try {
19688            final XmlSerializer serializer = new FastXmlSerializer();
19689            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19690            serializer.startDocument(null, true);
19691            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19692
19693            synchronized (mPackages) {
19694                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19695            }
19696
19697            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19698            serializer.endDocument();
19699            serializer.flush();
19700        } catch (Exception e) {
19701            if (DEBUG_BACKUP) {
19702                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19703            }
19704            return null;
19705        }
19706
19707        return dataStream.toByteArray();
19708    }
19709
19710    @Override
19711    public void restorePreferredActivities(byte[] backup, int userId) {
19712        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19713            throw new SecurityException("Only the system may call restorePreferredActivities()");
19714        }
19715
19716        try {
19717            final XmlPullParser parser = Xml.newPullParser();
19718            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19719            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19720                    new BlobXmlRestorer() {
19721                        @Override
19722                        public void apply(XmlPullParser parser, int userId)
19723                                throws XmlPullParserException, IOException {
19724                            synchronized (mPackages) {
19725                                mSettings.readPreferredActivitiesLPw(parser, userId);
19726                            }
19727                        }
19728                    } );
19729        } catch (Exception e) {
19730            if (DEBUG_BACKUP) {
19731                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19732            }
19733        }
19734    }
19735
19736    /**
19737     * Non-Binder method, support for the backup/restore mechanism: write the
19738     * default browser (etc) settings in its canonical XML format.  Returns the default
19739     * browser XML representation as a byte array, or null if there is none.
19740     */
19741    @Override
19742    public byte[] getDefaultAppsBackup(int userId) {
19743        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19744            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19745        }
19746
19747        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19748        try {
19749            final XmlSerializer serializer = new FastXmlSerializer();
19750            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19751            serializer.startDocument(null, true);
19752            serializer.startTag(null, TAG_DEFAULT_APPS);
19753
19754            synchronized (mPackages) {
19755                mSettings.writeDefaultAppsLPr(serializer, userId);
19756            }
19757
19758            serializer.endTag(null, TAG_DEFAULT_APPS);
19759            serializer.endDocument();
19760            serializer.flush();
19761        } catch (Exception e) {
19762            if (DEBUG_BACKUP) {
19763                Slog.e(TAG, "Unable to write default apps for backup", e);
19764            }
19765            return null;
19766        }
19767
19768        return dataStream.toByteArray();
19769    }
19770
19771    @Override
19772    public void restoreDefaultApps(byte[] backup, int userId) {
19773        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19774            throw new SecurityException("Only the system may call restoreDefaultApps()");
19775        }
19776
19777        try {
19778            final XmlPullParser parser = Xml.newPullParser();
19779            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19780            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19781                    new BlobXmlRestorer() {
19782                        @Override
19783                        public void apply(XmlPullParser parser, int userId)
19784                                throws XmlPullParserException, IOException {
19785                            synchronized (mPackages) {
19786                                mSettings.readDefaultAppsLPw(parser, userId);
19787                            }
19788                        }
19789                    } );
19790        } catch (Exception e) {
19791            if (DEBUG_BACKUP) {
19792                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19793            }
19794        }
19795    }
19796
19797    @Override
19798    public byte[] getIntentFilterVerificationBackup(int userId) {
19799        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19800            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19801        }
19802
19803        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19804        try {
19805            final XmlSerializer serializer = new FastXmlSerializer();
19806            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19807            serializer.startDocument(null, true);
19808            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19809
19810            synchronized (mPackages) {
19811                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19812            }
19813
19814            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19815            serializer.endDocument();
19816            serializer.flush();
19817        } catch (Exception e) {
19818            if (DEBUG_BACKUP) {
19819                Slog.e(TAG, "Unable to write default apps for backup", e);
19820            }
19821            return null;
19822        }
19823
19824        return dataStream.toByteArray();
19825    }
19826
19827    @Override
19828    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19829        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19830            throw new SecurityException("Only the system may call restorePreferredActivities()");
19831        }
19832
19833        try {
19834            final XmlPullParser parser = Xml.newPullParser();
19835            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19836            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19837                    new BlobXmlRestorer() {
19838                        @Override
19839                        public void apply(XmlPullParser parser, int userId)
19840                                throws XmlPullParserException, IOException {
19841                            synchronized (mPackages) {
19842                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19843                                mSettings.writeLPr();
19844                            }
19845                        }
19846                    } );
19847        } catch (Exception e) {
19848            if (DEBUG_BACKUP) {
19849                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19850            }
19851        }
19852    }
19853
19854    @Override
19855    public byte[] getPermissionGrantBackup(int userId) {
19856        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19857            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19858        }
19859
19860        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19861        try {
19862            final XmlSerializer serializer = new FastXmlSerializer();
19863            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19864            serializer.startDocument(null, true);
19865            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19866
19867            synchronized (mPackages) {
19868                serializeRuntimePermissionGrantsLPr(serializer, userId);
19869            }
19870
19871            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19872            serializer.endDocument();
19873            serializer.flush();
19874        } catch (Exception e) {
19875            if (DEBUG_BACKUP) {
19876                Slog.e(TAG, "Unable to write default apps for backup", e);
19877            }
19878            return null;
19879        }
19880
19881        return dataStream.toByteArray();
19882    }
19883
19884    @Override
19885    public void restorePermissionGrants(byte[] backup, int userId) {
19886        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19887            throw new SecurityException("Only the system may call restorePermissionGrants()");
19888        }
19889
19890        try {
19891            final XmlPullParser parser = Xml.newPullParser();
19892            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19893            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19894                    new BlobXmlRestorer() {
19895                        @Override
19896                        public void apply(XmlPullParser parser, int userId)
19897                                throws XmlPullParserException, IOException {
19898                            synchronized (mPackages) {
19899                                processRestoredPermissionGrantsLPr(parser, userId);
19900                            }
19901                        }
19902                    } );
19903        } catch (Exception e) {
19904            if (DEBUG_BACKUP) {
19905                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19906            }
19907        }
19908    }
19909
19910    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19911            throws IOException {
19912        serializer.startTag(null, TAG_ALL_GRANTS);
19913
19914        final int N = mSettings.mPackages.size();
19915        for (int i = 0; i < N; i++) {
19916            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19917            boolean pkgGrantsKnown = false;
19918
19919            PermissionsState packagePerms = ps.getPermissionsState();
19920
19921            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19922                final int grantFlags = state.getFlags();
19923                // only look at grants that are not system/policy fixed
19924                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19925                    final boolean isGranted = state.isGranted();
19926                    // And only back up the user-twiddled state bits
19927                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19928                        final String packageName = mSettings.mPackages.keyAt(i);
19929                        if (!pkgGrantsKnown) {
19930                            serializer.startTag(null, TAG_GRANT);
19931                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19932                            pkgGrantsKnown = true;
19933                        }
19934
19935                        final boolean userSet =
19936                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19937                        final boolean userFixed =
19938                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19939                        final boolean revoke =
19940                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19941
19942                        serializer.startTag(null, TAG_PERMISSION);
19943                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19944                        if (isGranted) {
19945                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19946                        }
19947                        if (userSet) {
19948                            serializer.attribute(null, ATTR_USER_SET, "true");
19949                        }
19950                        if (userFixed) {
19951                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19952                        }
19953                        if (revoke) {
19954                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19955                        }
19956                        serializer.endTag(null, TAG_PERMISSION);
19957                    }
19958                }
19959            }
19960
19961            if (pkgGrantsKnown) {
19962                serializer.endTag(null, TAG_GRANT);
19963            }
19964        }
19965
19966        serializer.endTag(null, TAG_ALL_GRANTS);
19967    }
19968
19969    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19970            throws XmlPullParserException, IOException {
19971        String pkgName = null;
19972        int outerDepth = parser.getDepth();
19973        int type;
19974        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19975                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19976            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19977                continue;
19978            }
19979
19980            final String tagName = parser.getName();
19981            if (tagName.equals(TAG_GRANT)) {
19982                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19983                if (DEBUG_BACKUP) {
19984                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19985                }
19986            } else if (tagName.equals(TAG_PERMISSION)) {
19987
19988                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19989                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19990
19991                int newFlagSet = 0;
19992                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19993                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19994                }
19995                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19996                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19997                }
19998                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19999                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20000                }
20001                if (DEBUG_BACKUP) {
20002                    Slog.v(TAG, "  + Restoring grant:"
20003                            + " pkg=" + pkgName
20004                            + " perm=" + permName
20005                            + " granted=" + isGranted
20006                            + " bits=0x" + Integer.toHexString(newFlagSet));
20007                }
20008                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20009                if (ps != null) {
20010                    // Already installed so we apply the grant immediately
20011                    if (DEBUG_BACKUP) {
20012                        Slog.v(TAG, "        + already installed; applying");
20013                    }
20014                    PermissionsState perms = ps.getPermissionsState();
20015                    BasePermission bp =
20016                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
20017                    if (bp != null) {
20018                        if (isGranted) {
20019                            perms.grantRuntimePermission(bp, userId);
20020                        }
20021                        if (newFlagSet != 0) {
20022                            perms.updatePermissionFlags(
20023                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20024                        }
20025                    }
20026                } else {
20027                    // Need to wait for post-restore install to apply the grant
20028                    if (DEBUG_BACKUP) {
20029                        Slog.v(TAG, "        - not yet installed; saving for later");
20030                    }
20031                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20032                            isGranted, newFlagSet, userId);
20033                }
20034            } else {
20035                PackageManagerService.reportSettingsProblem(Log.WARN,
20036                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20037                XmlUtils.skipCurrentTag(parser);
20038            }
20039        }
20040
20041        scheduleWriteSettingsLocked();
20042        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20043    }
20044
20045    @Override
20046    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20047            int sourceUserId, int targetUserId, int flags) {
20048        mContext.enforceCallingOrSelfPermission(
20049                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20050        int callingUid = Binder.getCallingUid();
20051        enforceOwnerRights(ownerPackage, callingUid);
20052        PackageManagerServiceUtils.enforceShellRestriction(
20053                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20054        if (intentFilter.countActions() == 0) {
20055            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20056            return;
20057        }
20058        synchronized (mPackages) {
20059            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20060                    ownerPackage, targetUserId, flags);
20061            CrossProfileIntentResolver resolver =
20062                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20063            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20064            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20065            if (existing != null) {
20066                int size = existing.size();
20067                for (int i = 0; i < size; i++) {
20068                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20069                        return;
20070                    }
20071                }
20072            }
20073            resolver.addFilter(newFilter);
20074            scheduleWritePackageRestrictionsLocked(sourceUserId);
20075        }
20076    }
20077
20078    @Override
20079    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20080        mContext.enforceCallingOrSelfPermission(
20081                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20082        final int callingUid = Binder.getCallingUid();
20083        enforceOwnerRights(ownerPackage, callingUid);
20084        PackageManagerServiceUtils.enforceShellRestriction(
20085                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20086        synchronized (mPackages) {
20087            CrossProfileIntentResolver resolver =
20088                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20089            ArraySet<CrossProfileIntentFilter> set =
20090                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20091            for (CrossProfileIntentFilter filter : set) {
20092                if (filter.getOwnerPackage().equals(ownerPackage)) {
20093                    resolver.removeFilter(filter);
20094                }
20095            }
20096            scheduleWritePackageRestrictionsLocked(sourceUserId);
20097        }
20098    }
20099
20100    // Enforcing that callingUid is owning pkg on userId
20101    private void enforceOwnerRights(String pkg, int callingUid) {
20102        // The system owns everything.
20103        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20104            return;
20105        }
20106        final int callingUserId = UserHandle.getUserId(callingUid);
20107        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20108        if (pi == null) {
20109            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20110                    + callingUserId);
20111        }
20112        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20113            throw new SecurityException("Calling uid " + callingUid
20114                    + " does not own package " + pkg);
20115        }
20116    }
20117
20118    @Override
20119    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20120        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20121            return null;
20122        }
20123        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20124    }
20125
20126    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20127        UserManagerService ums = UserManagerService.getInstance();
20128        if (ums != null) {
20129            final UserInfo parent = ums.getProfileParent(userId);
20130            final int launcherUid = (parent != null) ? parent.id : userId;
20131            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20132            if (launcherComponent != null) {
20133                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20134                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20135                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20136                        .setPackage(launcherComponent.getPackageName());
20137                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20138            }
20139        }
20140    }
20141
20142    /**
20143     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20144     * then reports the most likely home activity or null if there are more than one.
20145     */
20146    private ComponentName getDefaultHomeActivity(int userId) {
20147        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20148        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20149        if (cn != null) {
20150            return cn;
20151        }
20152
20153        // Find the launcher with the highest priority and return that component if there are no
20154        // other home activity with the same priority.
20155        int lastPriority = Integer.MIN_VALUE;
20156        ComponentName lastComponent = null;
20157        final int size = allHomeCandidates.size();
20158        for (int i = 0; i < size; i++) {
20159            final ResolveInfo ri = allHomeCandidates.get(i);
20160            if (ri.priority > lastPriority) {
20161                lastComponent = ri.activityInfo.getComponentName();
20162                lastPriority = ri.priority;
20163            } else if (ri.priority == lastPriority) {
20164                // Two components found with same priority.
20165                lastComponent = null;
20166            }
20167        }
20168        return lastComponent;
20169    }
20170
20171    private Intent getHomeIntent() {
20172        Intent intent = new Intent(Intent.ACTION_MAIN);
20173        intent.addCategory(Intent.CATEGORY_HOME);
20174        intent.addCategory(Intent.CATEGORY_DEFAULT);
20175        return intent;
20176    }
20177
20178    private IntentFilter getHomeFilter() {
20179        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20180        filter.addCategory(Intent.CATEGORY_HOME);
20181        filter.addCategory(Intent.CATEGORY_DEFAULT);
20182        return filter;
20183    }
20184
20185    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20186            int userId) {
20187        Intent intent  = getHomeIntent();
20188        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20189                PackageManager.GET_META_DATA, userId);
20190        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20191                true, false, false, userId);
20192
20193        allHomeCandidates.clear();
20194        if (list != null) {
20195            for (ResolveInfo ri : list) {
20196                allHomeCandidates.add(ri);
20197            }
20198        }
20199        return (preferred == null || preferred.activityInfo == null)
20200                ? null
20201                : new ComponentName(preferred.activityInfo.packageName,
20202                        preferred.activityInfo.name);
20203    }
20204
20205    @Override
20206    public void setHomeActivity(ComponentName comp, int userId) {
20207        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20208            return;
20209        }
20210        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20211        getHomeActivitiesAsUser(homeActivities, userId);
20212
20213        boolean found = false;
20214
20215        final int size = homeActivities.size();
20216        final ComponentName[] set = new ComponentName[size];
20217        for (int i = 0; i < size; i++) {
20218            final ResolveInfo candidate = homeActivities.get(i);
20219            final ActivityInfo info = candidate.activityInfo;
20220            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20221            set[i] = activityName;
20222            if (!found && activityName.equals(comp)) {
20223                found = true;
20224            }
20225        }
20226        if (!found) {
20227            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20228                    + userId);
20229        }
20230        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20231                set, comp, userId);
20232    }
20233
20234    private @Nullable String getSetupWizardPackageName() {
20235        final Intent intent = new Intent(Intent.ACTION_MAIN);
20236        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20237
20238        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20239                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20240                        | MATCH_DISABLED_COMPONENTS,
20241                UserHandle.myUserId());
20242        if (matches.size() == 1) {
20243            return matches.get(0).getComponentInfo().packageName;
20244        } else {
20245            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20246                    + ": matches=" + matches);
20247            return null;
20248        }
20249    }
20250
20251    private @Nullable String getStorageManagerPackageName() {
20252        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20253
20254        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20255                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20256                        | MATCH_DISABLED_COMPONENTS,
20257                UserHandle.myUserId());
20258        if (matches.size() == 1) {
20259            return matches.get(0).getComponentInfo().packageName;
20260        } else {
20261            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20262                    + matches.size() + ": matches=" + matches);
20263            return null;
20264        }
20265    }
20266
20267    @Override
20268    public void setApplicationEnabledSetting(String appPackageName,
20269            int newState, int flags, int userId, String callingPackage) {
20270        if (!sUserManager.exists(userId)) return;
20271        if (callingPackage == null) {
20272            callingPackage = Integer.toString(Binder.getCallingUid());
20273        }
20274        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20275    }
20276
20277    @Override
20278    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20279        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20280        synchronized (mPackages) {
20281            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20282            if (pkgSetting != null) {
20283                pkgSetting.setUpdateAvailable(updateAvailable);
20284            }
20285        }
20286    }
20287
20288    @Override
20289    public void setComponentEnabledSetting(ComponentName componentName,
20290            int newState, int flags, int userId) {
20291        if (!sUserManager.exists(userId)) return;
20292        setEnabledSetting(componentName.getPackageName(),
20293                componentName.getClassName(), newState, flags, userId, null);
20294    }
20295
20296    private void setEnabledSetting(final String packageName, String className, int newState,
20297            final int flags, int userId, String callingPackage) {
20298        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20299              || newState == COMPONENT_ENABLED_STATE_ENABLED
20300              || newState == COMPONENT_ENABLED_STATE_DISABLED
20301              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20302              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20303            throw new IllegalArgumentException("Invalid new component state: "
20304                    + newState);
20305        }
20306        PackageSetting pkgSetting;
20307        final int callingUid = Binder.getCallingUid();
20308        final int permission;
20309        if (callingUid == Process.SYSTEM_UID) {
20310            permission = PackageManager.PERMISSION_GRANTED;
20311        } else {
20312            permission = mContext.checkCallingOrSelfPermission(
20313                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20314        }
20315        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20316                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20317        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20318        boolean sendNow = false;
20319        boolean isApp = (className == null);
20320        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20321        String componentName = isApp ? packageName : className;
20322        int packageUid = -1;
20323        ArrayList<String> components;
20324
20325        // reader
20326        synchronized (mPackages) {
20327            pkgSetting = mSettings.mPackages.get(packageName);
20328            if (pkgSetting == null) {
20329                if (!isCallerInstantApp) {
20330                    if (className == null) {
20331                        throw new IllegalArgumentException("Unknown package: " + packageName);
20332                    }
20333                    throw new IllegalArgumentException(
20334                            "Unknown component: " + packageName + "/" + className);
20335                } else {
20336                    // throw SecurityException to prevent leaking package information
20337                    throw new SecurityException(
20338                            "Attempt to change component state; "
20339                            + "pid=" + Binder.getCallingPid()
20340                            + ", uid=" + callingUid
20341                            + (className == null
20342                                    ? ", package=" + packageName
20343                                    : ", component=" + packageName + "/" + className));
20344                }
20345            }
20346        }
20347
20348        // Limit who can change which apps
20349        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20350            // Don't allow apps that don't have permission to modify other apps
20351            if (!allowedByPermission
20352                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20353                throw new SecurityException(
20354                        "Attempt to change component state; "
20355                        + "pid=" + Binder.getCallingPid()
20356                        + ", uid=" + callingUid
20357                        + (className == null
20358                                ? ", package=" + packageName
20359                                : ", component=" + packageName + "/" + className));
20360            }
20361            // Don't allow changing protected packages.
20362            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20363                throw new SecurityException("Cannot disable a protected package: " + packageName);
20364            }
20365        }
20366
20367        synchronized (mPackages) {
20368            if (callingUid == Process.SHELL_UID
20369                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20370                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20371                // unless it is a test package.
20372                int oldState = pkgSetting.getEnabled(userId);
20373                if (className == null
20374                        &&
20375                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20376                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20377                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20378                        &&
20379                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20380                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20381                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20382                    // ok
20383                } else {
20384                    throw new SecurityException(
20385                            "Shell cannot change component state for " + packageName + "/"
20386                                    + className + " to " + newState);
20387                }
20388            }
20389        }
20390        if (className == null) {
20391            // We're dealing with an application/package level state change
20392            synchronized (mPackages) {
20393                if (pkgSetting.getEnabled(userId) == newState) {
20394                    // Nothing to do
20395                    return;
20396                }
20397            }
20398            // If we're enabling a system stub, there's a little more work to do.
20399            // Prior to enabling the package, we need to decompress the APK(s) to the
20400            // data partition and then replace the version on the system partition.
20401            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20402            final boolean isSystemStub = deletedPkg.isStub
20403                    && deletedPkg.isSystem();
20404            if (isSystemStub
20405                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20406                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20407                final File codePath = decompressPackage(deletedPkg);
20408                if (codePath == null) {
20409                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20410                    return;
20411                }
20412                // TODO remove direct parsing of the package object during internal cleanup
20413                // of scan package
20414                // We need to call parse directly here for no other reason than we need
20415                // the new package in order to disable the old one [we use the information
20416                // for some internal optimization to optionally create a new package setting
20417                // object on replace]. However, we can't get the package from the scan
20418                // because the scan modifies live structures and we need to remove the
20419                // old [system] package from the system before a scan can be attempted.
20420                // Once scan is indempotent we can remove this parse and use the package
20421                // object we scanned, prior to adding it to package settings.
20422                final PackageParser pp = new PackageParser();
20423                pp.setSeparateProcesses(mSeparateProcesses);
20424                pp.setDisplayMetrics(mMetrics);
20425                pp.setCallback(mPackageParserCallback);
20426                final PackageParser.Package tmpPkg;
20427                try {
20428                    final @ParseFlags int parseFlags = mDefParseFlags
20429                            | PackageParser.PARSE_MUST_BE_APK
20430                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20431                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20432                } catch (PackageParserException e) {
20433                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20434                    return;
20435                }
20436                synchronized (mInstallLock) {
20437                    // Disable the stub and remove any package entries
20438                    removePackageLI(deletedPkg, true);
20439                    synchronized (mPackages) {
20440                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20441                    }
20442                    final PackageParser.Package pkg;
20443                    try (PackageFreezer freezer =
20444                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20445                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20446                                | PackageParser.PARSE_ENFORCE_CODE;
20447                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20448                                0 /*currentTime*/, null /*user*/);
20449                        prepareAppDataAfterInstallLIF(pkg);
20450                        synchronized (mPackages) {
20451                            try {
20452                                updateSharedLibrariesLPr(pkg, null);
20453                            } catch (PackageManagerException e) {
20454                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20455                            }
20456                            mPermissionManager.updatePermissions(
20457                                    pkg.packageName, pkg, true, mPackages.values(),
20458                                    mPermissionCallback);
20459                            mSettings.writeLPr();
20460                        }
20461                    } catch (PackageManagerException e) {
20462                        // Whoops! Something went wrong; try to roll back to the stub
20463                        Slog.w(TAG, "Failed to install compressed system package:"
20464                                + pkgSetting.name, e);
20465                        // Remove the failed install
20466                        removeCodePathLI(codePath);
20467
20468                        // Install the system package
20469                        try (PackageFreezer freezer =
20470                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20471                            synchronized (mPackages) {
20472                                // NOTE: The system package always needs to be enabled; even
20473                                // if it's for a compressed stub. If we don't, installing the
20474                                // system package fails during scan [scanning checks the disabled
20475                                // packages]. We will reverse this later, after we've "installed"
20476                                // the stub.
20477                                // This leaves us in a fragile state; the stub should never be
20478                                // enabled, so, cross your fingers and hope nothing goes wrong
20479                                // until we can disable the package later.
20480                                enableSystemPackageLPw(deletedPkg);
20481                            }
20482                            installPackageFromSystemLIF(deletedPkg.codePath,
20483                                    false /*isPrivileged*/, null /*allUserHandles*/,
20484                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20485                                    true /*writeSettings*/);
20486                        } catch (PackageManagerException pme) {
20487                            Slog.w(TAG, "Failed to restore system package:"
20488                                    + deletedPkg.packageName, pme);
20489                        } finally {
20490                            synchronized (mPackages) {
20491                                mSettings.disableSystemPackageLPw(
20492                                        deletedPkg.packageName, true /*replaced*/);
20493                                mSettings.writeLPr();
20494                            }
20495                        }
20496                        return;
20497                    }
20498                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20499                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20500                    mDexManager.notifyPackageUpdated(pkg.packageName,
20501                            pkg.baseCodePath, pkg.splitCodePaths);
20502                }
20503            }
20504            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20505                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20506                // Don't care about who enables an app.
20507                callingPackage = null;
20508            }
20509            synchronized (mPackages) {
20510                pkgSetting.setEnabled(newState, userId, callingPackage);
20511            }
20512        } else {
20513            synchronized (mPackages) {
20514                // We're dealing with a component level state change
20515                // First, verify that this is a valid class name.
20516                PackageParser.Package pkg = pkgSetting.pkg;
20517                if (pkg == null || !pkg.hasComponentClassName(className)) {
20518                    if (pkg != null &&
20519                            pkg.applicationInfo.targetSdkVersion >=
20520                                    Build.VERSION_CODES.JELLY_BEAN) {
20521                        throw new IllegalArgumentException("Component class " + className
20522                                + " does not exist in " + packageName);
20523                    } else {
20524                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20525                                + className + " does not exist in " + packageName);
20526                    }
20527                }
20528                switch (newState) {
20529                    case COMPONENT_ENABLED_STATE_ENABLED:
20530                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20531                            return;
20532                        }
20533                        break;
20534                    case COMPONENT_ENABLED_STATE_DISABLED:
20535                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20536                            return;
20537                        }
20538                        break;
20539                    case COMPONENT_ENABLED_STATE_DEFAULT:
20540                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20541                            return;
20542                        }
20543                        break;
20544                    default:
20545                        Slog.e(TAG, "Invalid new component state: " + newState);
20546                        return;
20547                }
20548            }
20549        }
20550        synchronized (mPackages) {
20551            scheduleWritePackageRestrictionsLocked(userId);
20552            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20553            final long callingId = Binder.clearCallingIdentity();
20554            try {
20555                updateInstantAppInstallerLocked(packageName);
20556            } finally {
20557                Binder.restoreCallingIdentity(callingId);
20558            }
20559            components = mPendingBroadcasts.get(userId, packageName);
20560            final boolean newPackage = components == null;
20561            if (newPackage) {
20562                components = new ArrayList<String>();
20563            }
20564            if (!components.contains(componentName)) {
20565                components.add(componentName);
20566            }
20567            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20568                sendNow = true;
20569                // Purge entry from pending broadcast list if another one exists already
20570                // since we are sending one right away.
20571                mPendingBroadcasts.remove(userId, packageName);
20572            } else {
20573                if (newPackage) {
20574                    mPendingBroadcasts.put(userId, packageName, components);
20575                }
20576                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20577                    // Schedule a message
20578                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20579                }
20580            }
20581        }
20582
20583        long callingId = Binder.clearCallingIdentity();
20584        try {
20585            if (sendNow) {
20586                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20587                sendPackageChangedBroadcast(packageName,
20588                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20589            }
20590        } finally {
20591            Binder.restoreCallingIdentity(callingId);
20592        }
20593    }
20594
20595    @Override
20596    public void flushPackageRestrictionsAsUser(int userId) {
20597        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20598            return;
20599        }
20600        if (!sUserManager.exists(userId)) {
20601            return;
20602        }
20603        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20604                false /* checkShell */, "flushPackageRestrictions");
20605        synchronized (mPackages) {
20606            mSettings.writePackageRestrictionsLPr(userId);
20607            mDirtyUsers.remove(userId);
20608            if (mDirtyUsers.isEmpty()) {
20609                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20610            }
20611        }
20612    }
20613
20614    private void sendPackageChangedBroadcast(String packageName,
20615            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20616        if (DEBUG_INSTALL)
20617            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20618                    + componentNames);
20619        Bundle extras = new Bundle(4);
20620        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20621        String nameList[] = new String[componentNames.size()];
20622        componentNames.toArray(nameList);
20623        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20624        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20625        extras.putInt(Intent.EXTRA_UID, packageUid);
20626        // If this is not reporting a change of the overall package, then only send it
20627        // to registered receivers.  We don't want to launch a swath of apps for every
20628        // little component state change.
20629        final int flags = !componentNames.contains(packageName)
20630                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20631        final int userId = UserHandle.getUserId(packageUid);
20632        final boolean isInstantApp = isInstantApp(packageName, userId);
20633        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20634        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20635        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20636                userIds, instantUserIds);
20637    }
20638
20639    @Override
20640    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20641        if (!sUserManager.exists(userId)) return;
20642        final int callingUid = Binder.getCallingUid();
20643        if (getInstantAppPackageName(callingUid) != null) {
20644            return;
20645        }
20646        final int permission = mContext.checkCallingOrSelfPermission(
20647                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20648        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20649        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20650                true /* requireFullPermission */, true /* checkShell */, "stop package");
20651        // writer
20652        synchronized (mPackages) {
20653            final PackageSetting ps = mSettings.mPackages.get(packageName);
20654            if (!filterAppAccessLPr(ps, callingUid, userId)
20655                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20656                            allowedByPermission, callingUid, userId)) {
20657                scheduleWritePackageRestrictionsLocked(userId);
20658            }
20659        }
20660    }
20661
20662    @Override
20663    public String getInstallerPackageName(String packageName) {
20664        final int callingUid = Binder.getCallingUid();
20665        if (getInstantAppPackageName(callingUid) != null) {
20666            return null;
20667        }
20668        // reader
20669        synchronized (mPackages) {
20670            final PackageSetting ps = mSettings.mPackages.get(packageName);
20671            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20672                return null;
20673            }
20674            return mSettings.getInstallerPackageNameLPr(packageName);
20675        }
20676    }
20677
20678    public boolean isOrphaned(String packageName) {
20679        // reader
20680        synchronized (mPackages) {
20681            return mSettings.isOrphaned(packageName);
20682        }
20683    }
20684
20685    @Override
20686    public int getApplicationEnabledSetting(String packageName, int userId) {
20687        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20688        int callingUid = Binder.getCallingUid();
20689        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20690                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20691        // reader
20692        synchronized (mPackages) {
20693            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20694                return COMPONENT_ENABLED_STATE_DISABLED;
20695            }
20696            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20697        }
20698    }
20699
20700    @Override
20701    public int getComponentEnabledSetting(ComponentName component, int userId) {
20702        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20703        int callingUid = Binder.getCallingUid();
20704        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20705                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20706        synchronized (mPackages) {
20707            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20708                    component, TYPE_UNKNOWN, userId)) {
20709                return COMPONENT_ENABLED_STATE_DISABLED;
20710            }
20711            return mSettings.getComponentEnabledSettingLPr(component, userId);
20712        }
20713    }
20714
20715    @Override
20716    public void enterSafeMode() {
20717        enforceSystemOrRoot("Only the system can request entering safe mode");
20718
20719        if (!mSystemReady) {
20720            mSafeMode = true;
20721        }
20722    }
20723
20724    @Override
20725    public void systemReady() {
20726        enforceSystemOrRoot("Only the system can claim the system is ready");
20727
20728        mSystemReady = true;
20729        final ContentResolver resolver = mContext.getContentResolver();
20730        ContentObserver co = new ContentObserver(mHandler) {
20731            @Override
20732            public void onChange(boolean selfChange) {
20733                mEphemeralAppsDisabled =
20734                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20735                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20736            }
20737        };
20738        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20739                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20740                false, co, UserHandle.USER_SYSTEM);
20741        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20742                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20743        co.onChange(true);
20744
20745        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20746        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20747        // it is done.
20748        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20749            @Override
20750            public void onChange(boolean selfChange) {
20751                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20752                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20753                        oobEnabled == 1 ? "true" : "false");
20754            }
20755        };
20756        mContext.getContentResolver().registerContentObserver(
20757                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20758                UserHandle.USER_SYSTEM);
20759        // At boot, restore the value from the setting, which persists across reboot.
20760        privAppOobObserver.onChange(true);
20761
20762        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20763        // disabled after already being started.
20764        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20765                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20766
20767        // Read the compatibilty setting when the system is ready.
20768        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20769                mContext.getContentResolver(),
20770                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20771        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20772        if (DEBUG_SETTINGS) {
20773            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20774        }
20775
20776        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20777
20778        synchronized (mPackages) {
20779            // Verify that all of the preferred activity components actually
20780            // exist.  It is possible for applications to be updated and at
20781            // that point remove a previously declared activity component that
20782            // had been set as a preferred activity.  We try to clean this up
20783            // the next time we encounter that preferred activity, but it is
20784            // possible for the user flow to never be able to return to that
20785            // situation so here we do a sanity check to make sure we haven't
20786            // left any junk around.
20787            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20788            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20789                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20790                removed.clear();
20791                for (PreferredActivity pa : pir.filterSet()) {
20792                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20793                        removed.add(pa);
20794                    }
20795                }
20796                if (removed.size() > 0) {
20797                    for (int r=0; r<removed.size(); r++) {
20798                        PreferredActivity pa = removed.get(r);
20799                        Slog.w(TAG, "Removing dangling preferred activity: "
20800                                + pa.mPref.mComponent);
20801                        pir.removeFilter(pa);
20802                    }
20803                    mSettings.writePackageRestrictionsLPr(
20804                            mSettings.mPreferredActivities.keyAt(i));
20805                }
20806            }
20807
20808            for (int userId : UserManagerService.getInstance().getUserIds()) {
20809                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20810                    grantPermissionsUserIds = ArrayUtils.appendInt(
20811                            grantPermissionsUserIds, userId);
20812                }
20813            }
20814        }
20815        sUserManager.systemReady();
20816        // If we upgraded grant all default permissions before kicking off.
20817        for (int userId : grantPermissionsUserIds) {
20818            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20819        }
20820
20821        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20822            // If we did not grant default permissions, we preload from this the
20823            // default permission exceptions lazily to ensure we don't hit the
20824            // disk on a new user creation.
20825            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20826        }
20827
20828        // Now that we've scanned all packages, and granted any default
20829        // permissions, ensure permissions are updated. Beware of dragons if you
20830        // try optimizing this.
20831        synchronized (mPackages) {
20832            mPermissionManager.updateAllPermissions(
20833                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
20834                    mPermissionCallback);
20835        }
20836
20837        // Kick off any messages waiting for system ready
20838        if (mPostSystemReadyMessages != null) {
20839            for (Message msg : mPostSystemReadyMessages) {
20840                msg.sendToTarget();
20841            }
20842            mPostSystemReadyMessages = null;
20843        }
20844
20845        // Watch for external volumes that come and go over time
20846        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20847        storage.registerListener(mStorageListener);
20848
20849        mInstallerService.systemReady();
20850        mPackageDexOptimizer.systemReady();
20851
20852        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20853                StorageManagerInternal.class);
20854        StorageManagerInternal.addExternalStoragePolicy(
20855                new StorageManagerInternal.ExternalStorageMountPolicy() {
20856            @Override
20857            public int getMountMode(int uid, String packageName) {
20858                if (Process.isIsolated(uid)) {
20859                    return Zygote.MOUNT_EXTERNAL_NONE;
20860                }
20861                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20862                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20863                }
20864                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20865                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20866                }
20867                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20868                    return Zygote.MOUNT_EXTERNAL_READ;
20869                }
20870                return Zygote.MOUNT_EXTERNAL_WRITE;
20871            }
20872
20873            @Override
20874            public boolean hasExternalStorage(int uid, String packageName) {
20875                return true;
20876            }
20877        });
20878
20879        // Now that we're mostly running, clean up stale users and apps
20880        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20881        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20882
20883        mPermissionManager.systemReady();
20884    }
20885
20886    public void waitForAppDataPrepared() {
20887        if (mPrepareAppDataFuture == null) {
20888            return;
20889        }
20890        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20891        mPrepareAppDataFuture = null;
20892    }
20893
20894    @Override
20895    public boolean isSafeMode() {
20896        // allow instant applications
20897        return mSafeMode;
20898    }
20899
20900    @Override
20901    public boolean hasSystemUidErrors() {
20902        // allow instant applications
20903        return mHasSystemUidErrors;
20904    }
20905
20906    static String arrayToString(int[] array) {
20907        StringBuffer buf = new StringBuffer(128);
20908        buf.append('[');
20909        if (array != null) {
20910            for (int i=0; i<array.length; i++) {
20911                if (i > 0) buf.append(", ");
20912                buf.append(array[i]);
20913            }
20914        }
20915        buf.append(']');
20916        return buf.toString();
20917    }
20918
20919    @Override
20920    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20921            FileDescriptor err, String[] args, ShellCallback callback,
20922            ResultReceiver resultReceiver) {
20923        (new PackageManagerShellCommand(this)).exec(
20924                this, in, out, err, args, callback, resultReceiver);
20925    }
20926
20927    @Override
20928    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20929        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20930
20931        DumpState dumpState = new DumpState();
20932        boolean fullPreferred = false;
20933        boolean checkin = false;
20934
20935        String packageName = null;
20936        ArraySet<String> permissionNames = null;
20937
20938        int opti = 0;
20939        while (opti < args.length) {
20940            String opt = args[opti];
20941            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20942                break;
20943            }
20944            opti++;
20945
20946            if ("-a".equals(opt)) {
20947                // Right now we only know how to print all.
20948            } else if ("-h".equals(opt)) {
20949                pw.println("Package manager dump options:");
20950                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20951                pw.println("    --checkin: dump for a checkin");
20952                pw.println("    -f: print details of intent filters");
20953                pw.println("    -h: print this help");
20954                pw.println("  cmd may be one of:");
20955                pw.println("    l[ibraries]: list known shared libraries");
20956                pw.println("    f[eatures]: list device features");
20957                pw.println("    k[eysets]: print known keysets");
20958                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20959                pw.println("    perm[issions]: dump permissions");
20960                pw.println("    permission [name ...]: dump declaration and use of given permission");
20961                pw.println("    pref[erred]: print preferred package settings");
20962                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20963                pw.println("    prov[iders]: dump content providers");
20964                pw.println("    p[ackages]: dump installed packages");
20965                pw.println("    s[hared-users]: dump shared user IDs");
20966                pw.println("    m[essages]: print collected runtime messages");
20967                pw.println("    v[erifiers]: print package verifier info");
20968                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20969                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20970                pw.println("    version: print database version info");
20971                pw.println("    write: write current settings now");
20972                pw.println("    installs: details about install sessions");
20973                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20974                pw.println("    dexopt: dump dexopt state");
20975                pw.println("    compiler-stats: dump compiler statistics");
20976                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20977                pw.println("    service-permissions: dump permissions required by services");
20978                pw.println("    <package.name>: info about given package");
20979                return;
20980            } else if ("--checkin".equals(opt)) {
20981                checkin = true;
20982            } else if ("-f".equals(opt)) {
20983                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20984            } else if ("--proto".equals(opt)) {
20985                dumpProto(fd);
20986                return;
20987            } else {
20988                pw.println("Unknown argument: " + opt + "; use -h for help");
20989            }
20990        }
20991
20992        // Is the caller requesting to dump a particular piece of data?
20993        if (opti < args.length) {
20994            String cmd = args[opti];
20995            opti++;
20996            // Is this a package name?
20997            if ("android".equals(cmd) || cmd.contains(".")) {
20998                packageName = cmd;
20999                // When dumping a single package, we always dump all of its
21000                // filter information since the amount of data will be reasonable.
21001                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21002            } else if ("check-permission".equals(cmd)) {
21003                if (opti >= args.length) {
21004                    pw.println("Error: check-permission missing permission argument");
21005                    return;
21006                }
21007                String perm = args[opti];
21008                opti++;
21009                if (opti >= args.length) {
21010                    pw.println("Error: check-permission missing package argument");
21011                    return;
21012                }
21013
21014                String pkg = args[opti];
21015                opti++;
21016                int user = UserHandle.getUserId(Binder.getCallingUid());
21017                if (opti < args.length) {
21018                    try {
21019                        user = Integer.parseInt(args[opti]);
21020                    } catch (NumberFormatException e) {
21021                        pw.println("Error: check-permission user argument is not a number: "
21022                                + args[opti]);
21023                        return;
21024                    }
21025                }
21026
21027                // Normalize package name to handle renamed packages and static libs
21028                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21029
21030                pw.println(checkPermission(perm, pkg, user));
21031                return;
21032            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21033                dumpState.setDump(DumpState.DUMP_LIBS);
21034            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21035                dumpState.setDump(DumpState.DUMP_FEATURES);
21036            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21037                if (opti >= args.length) {
21038                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21039                            | DumpState.DUMP_SERVICE_RESOLVERS
21040                            | DumpState.DUMP_RECEIVER_RESOLVERS
21041                            | DumpState.DUMP_CONTENT_RESOLVERS);
21042                } else {
21043                    while (opti < args.length) {
21044                        String name = args[opti];
21045                        if ("a".equals(name) || "activity".equals(name)) {
21046                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21047                        } else if ("s".equals(name) || "service".equals(name)) {
21048                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21049                        } else if ("r".equals(name) || "receiver".equals(name)) {
21050                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21051                        } else if ("c".equals(name) || "content".equals(name)) {
21052                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21053                        } else {
21054                            pw.println("Error: unknown resolver table type: " + name);
21055                            return;
21056                        }
21057                        opti++;
21058                    }
21059                }
21060            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21061                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21062            } else if ("permission".equals(cmd)) {
21063                if (opti >= args.length) {
21064                    pw.println("Error: permission requires permission name");
21065                    return;
21066                }
21067                permissionNames = new ArraySet<>();
21068                while (opti < args.length) {
21069                    permissionNames.add(args[opti]);
21070                    opti++;
21071                }
21072                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21073                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21074            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21075                dumpState.setDump(DumpState.DUMP_PREFERRED);
21076            } else if ("preferred-xml".equals(cmd)) {
21077                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21078                if (opti < args.length && "--full".equals(args[opti])) {
21079                    fullPreferred = true;
21080                    opti++;
21081                }
21082            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21083                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21084            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21085                dumpState.setDump(DumpState.DUMP_PACKAGES);
21086            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21087                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21088            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21089                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21090            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21091                dumpState.setDump(DumpState.DUMP_MESSAGES);
21092            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21093                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21094            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21095                    || "intent-filter-verifiers".equals(cmd)) {
21096                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21097            } else if ("version".equals(cmd)) {
21098                dumpState.setDump(DumpState.DUMP_VERSION);
21099            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21100                dumpState.setDump(DumpState.DUMP_KEYSETS);
21101            } else if ("installs".equals(cmd)) {
21102                dumpState.setDump(DumpState.DUMP_INSTALLS);
21103            } else if ("frozen".equals(cmd)) {
21104                dumpState.setDump(DumpState.DUMP_FROZEN);
21105            } else if ("volumes".equals(cmd)) {
21106                dumpState.setDump(DumpState.DUMP_VOLUMES);
21107            } else if ("dexopt".equals(cmd)) {
21108                dumpState.setDump(DumpState.DUMP_DEXOPT);
21109            } else if ("compiler-stats".equals(cmd)) {
21110                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21111            } else if ("changes".equals(cmd)) {
21112                dumpState.setDump(DumpState.DUMP_CHANGES);
21113            } else if ("service-permissions".equals(cmd)) {
21114                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
21115            } else if ("write".equals(cmd)) {
21116                synchronized (mPackages) {
21117                    mSettings.writeLPr();
21118                    pw.println("Settings written.");
21119                    return;
21120                }
21121            }
21122        }
21123
21124        if (checkin) {
21125            pw.println("vers,1");
21126        }
21127
21128        // reader
21129        synchronized (mPackages) {
21130            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21131                if (!checkin) {
21132                    if (dumpState.onTitlePrinted())
21133                        pw.println();
21134                    pw.println("Database versions:");
21135                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21136                }
21137            }
21138
21139            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21140                if (!checkin) {
21141                    if (dumpState.onTitlePrinted())
21142                        pw.println();
21143                    pw.println("Verifiers:");
21144                    pw.print("  Required: ");
21145                    pw.print(mRequiredVerifierPackage);
21146                    pw.print(" (uid=");
21147                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21148                            UserHandle.USER_SYSTEM));
21149                    pw.println(")");
21150                } else if (mRequiredVerifierPackage != null) {
21151                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21152                    pw.print(",");
21153                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21154                            UserHandle.USER_SYSTEM));
21155                }
21156            }
21157
21158            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21159                    packageName == null) {
21160                if (mIntentFilterVerifierComponent != null) {
21161                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21162                    if (!checkin) {
21163                        if (dumpState.onTitlePrinted())
21164                            pw.println();
21165                        pw.println("Intent Filter Verifier:");
21166                        pw.print("  Using: ");
21167                        pw.print(verifierPackageName);
21168                        pw.print(" (uid=");
21169                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21170                                UserHandle.USER_SYSTEM));
21171                        pw.println(")");
21172                    } else if (verifierPackageName != null) {
21173                        pw.print("ifv,"); pw.print(verifierPackageName);
21174                        pw.print(",");
21175                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21176                                UserHandle.USER_SYSTEM));
21177                    }
21178                } else {
21179                    pw.println();
21180                    pw.println("No Intent Filter Verifier available!");
21181                }
21182            }
21183
21184            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21185                boolean printedHeader = false;
21186                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21187                while (it.hasNext()) {
21188                    String libName = it.next();
21189                    LongSparseArray<SharedLibraryEntry> versionedLib
21190                            = mSharedLibraries.get(libName);
21191                    if (versionedLib == null) {
21192                        continue;
21193                    }
21194                    final int versionCount = versionedLib.size();
21195                    for (int i = 0; i < versionCount; i++) {
21196                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21197                        if (!checkin) {
21198                            if (!printedHeader) {
21199                                if (dumpState.onTitlePrinted())
21200                                    pw.println();
21201                                pw.println("Libraries:");
21202                                printedHeader = true;
21203                            }
21204                            pw.print("  ");
21205                        } else {
21206                            pw.print("lib,");
21207                        }
21208                        pw.print(libEntry.info.getName());
21209                        if (libEntry.info.isStatic()) {
21210                            pw.print(" version=" + libEntry.info.getLongVersion());
21211                        }
21212                        if (!checkin) {
21213                            pw.print(" -> ");
21214                        }
21215                        if (libEntry.path != null) {
21216                            pw.print(" (jar) ");
21217                            pw.print(libEntry.path);
21218                        } else {
21219                            pw.print(" (apk) ");
21220                            pw.print(libEntry.apk);
21221                        }
21222                        pw.println();
21223                    }
21224                }
21225            }
21226
21227            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21228                if (dumpState.onTitlePrinted())
21229                    pw.println();
21230                if (!checkin) {
21231                    pw.println("Features:");
21232                }
21233
21234                synchronized (mAvailableFeatures) {
21235                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21236                        if (checkin) {
21237                            pw.print("feat,");
21238                            pw.print(feat.name);
21239                            pw.print(",");
21240                            pw.println(feat.version);
21241                        } else {
21242                            pw.print("  ");
21243                            pw.print(feat.name);
21244                            if (feat.version > 0) {
21245                                pw.print(" version=");
21246                                pw.print(feat.version);
21247                            }
21248                            pw.println();
21249                        }
21250                    }
21251                }
21252            }
21253
21254            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21255                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21256                        : "Activity Resolver Table:", "  ", packageName,
21257                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21258                    dumpState.setTitlePrinted(true);
21259                }
21260            }
21261            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21262                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21263                        : "Receiver Resolver Table:", "  ", packageName,
21264                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21265                    dumpState.setTitlePrinted(true);
21266                }
21267            }
21268            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21269                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21270                        : "Service Resolver Table:", "  ", packageName,
21271                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21272                    dumpState.setTitlePrinted(true);
21273                }
21274            }
21275            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21276                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21277                        : "Provider Resolver Table:", "  ", packageName,
21278                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21279                    dumpState.setTitlePrinted(true);
21280                }
21281            }
21282
21283            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21284                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21285                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21286                    int user = mSettings.mPreferredActivities.keyAt(i);
21287                    if (pir.dump(pw,
21288                            dumpState.getTitlePrinted()
21289                                ? "\nPreferred Activities User " + user + ":"
21290                                : "Preferred Activities User " + user + ":", "  ",
21291                            packageName, true, false)) {
21292                        dumpState.setTitlePrinted(true);
21293                    }
21294                }
21295            }
21296
21297            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21298                pw.flush();
21299                FileOutputStream fout = new FileOutputStream(fd);
21300                BufferedOutputStream str = new BufferedOutputStream(fout);
21301                XmlSerializer serializer = new FastXmlSerializer();
21302                try {
21303                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21304                    serializer.startDocument(null, true);
21305                    serializer.setFeature(
21306                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21307                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21308                    serializer.endDocument();
21309                    serializer.flush();
21310                } catch (IllegalArgumentException e) {
21311                    pw.println("Failed writing: " + e);
21312                } catch (IllegalStateException e) {
21313                    pw.println("Failed writing: " + e);
21314                } catch (IOException e) {
21315                    pw.println("Failed writing: " + e);
21316                }
21317            }
21318
21319            if (!checkin
21320                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21321                    && packageName == null) {
21322                pw.println();
21323                int count = mSettings.mPackages.size();
21324                if (count == 0) {
21325                    pw.println("No applications!");
21326                    pw.println();
21327                } else {
21328                    final String prefix = "  ";
21329                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21330                    if (allPackageSettings.size() == 0) {
21331                        pw.println("No domain preferred apps!");
21332                        pw.println();
21333                    } else {
21334                        pw.println("App verification status:");
21335                        pw.println();
21336                        count = 0;
21337                        for (PackageSetting ps : allPackageSettings) {
21338                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21339                            if (ivi == null || ivi.getPackageName() == null) continue;
21340                            pw.println(prefix + "Package: " + ivi.getPackageName());
21341                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21342                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21343                            pw.println();
21344                            count++;
21345                        }
21346                        if (count == 0) {
21347                            pw.println(prefix + "No app verification established.");
21348                            pw.println();
21349                        }
21350                        for (int userId : sUserManager.getUserIds()) {
21351                            pw.println("App linkages for user " + userId + ":");
21352                            pw.println();
21353                            count = 0;
21354                            for (PackageSetting ps : allPackageSettings) {
21355                                final long status = ps.getDomainVerificationStatusForUser(userId);
21356                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21357                                        && !DEBUG_DOMAIN_VERIFICATION) {
21358                                    continue;
21359                                }
21360                                pw.println(prefix + "Package: " + ps.name);
21361                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21362                                String statusStr = IntentFilterVerificationInfo.
21363                                        getStatusStringFromValue(status);
21364                                pw.println(prefix + "Status:  " + statusStr);
21365                                pw.println();
21366                                count++;
21367                            }
21368                            if (count == 0) {
21369                                pw.println(prefix + "No configured app linkages.");
21370                                pw.println();
21371                            }
21372                        }
21373                    }
21374                }
21375            }
21376
21377            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21378                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21379            }
21380
21381            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21382                boolean printedSomething = false;
21383                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21384                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21385                        continue;
21386                    }
21387                    if (!printedSomething) {
21388                        if (dumpState.onTitlePrinted())
21389                            pw.println();
21390                        pw.println("Registered ContentProviders:");
21391                        printedSomething = true;
21392                    }
21393                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21394                    pw.print("    "); pw.println(p.toString());
21395                }
21396                printedSomething = false;
21397                for (Map.Entry<String, PackageParser.Provider> entry :
21398                        mProvidersByAuthority.entrySet()) {
21399                    PackageParser.Provider p = entry.getValue();
21400                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21401                        continue;
21402                    }
21403                    if (!printedSomething) {
21404                        if (dumpState.onTitlePrinted())
21405                            pw.println();
21406                        pw.println("ContentProvider Authorities:");
21407                        printedSomething = true;
21408                    }
21409                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21410                    pw.print("    "); pw.println(p.toString());
21411                    if (p.info != null && p.info.applicationInfo != null) {
21412                        final String appInfo = p.info.applicationInfo.toString();
21413                        pw.print("      applicationInfo="); pw.println(appInfo);
21414                    }
21415                }
21416            }
21417
21418            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21419                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21420            }
21421
21422            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21423                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21424            }
21425
21426            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21427                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21428            }
21429
21430            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21431                if (dumpState.onTitlePrinted()) pw.println();
21432                pw.println("Package Changes:");
21433                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21434                final int K = mChangedPackages.size();
21435                for (int i = 0; i < K; i++) {
21436                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21437                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21438                    final int N = changes.size();
21439                    if (N == 0) {
21440                        pw.print("    "); pw.println("No packages changed");
21441                    } else {
21442                        for (int j = 0; j < N; j++) {
21443                            final String pkgName = changes.valueAt(j);
21444                            final int sequenceNumber = changes.keyAt(j);
21445                            pw.print("    ");
21446                            pw.print("seq=");
21447                            pw.print(sequenceNumber);
21448                            pw.print(", package=");
21449                            pw.println(pkgName);
21450                        }
21451                    }
21452                }
21453            }
21454
21455            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21456                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21457            }
21458
21459            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21460                // XXX should handle packageName != null by dumping only install data that
21461                // the given package is involved with.
21462                if (dumpState.onTitlePrinted()) pw.println();
21463
21464                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21465                ipw.println();
21466                ipw.println("Frozen packages:");
21467                ipw.increaseIndent();
21468                if (mFrozenPackages.size() == 0) {
21469                    ipw.println("(none)");
21470                } else {
21471                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21472                        ipw.println(mFrozenPackages.valueAt(i));
21473                    }
21474                }
21475                ipw.decreaseIndent();
21476            }
21477
21478            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21479                if (dumpState.onTitlePrinted()) pw.println();
21480
21481                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21482                ipw.println();
21483                ipw.println("Loaded volumes:");
21484                ipw.increaseIndent();
21485                if (mLoadedVolumes.size() == 0) {
21486                    ipw.println("(none)");
21487                } else {
21488                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
21489                        ipw.println(mLoadedVolumes.valueAt(i));
21490                    }
21491                }
21492                ipw.decreaseIndent();
21493            }
21494
21495            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21496                    && packageName == null) {
21497                if (dumpState.onTitlePrinted()) pw.println();
21498                pw.println("Service permissions:");
21499
21500                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21501                while (filterIterator.hasNext()) {
21502                    final ServiceIntentInfo info = filterIterator.next();
21503                    final ServiceInfo serviceInfo = info.service.info;
21504                    final String permission = serviceInfo.permission;
21505                    if (permission != null) {
21506                        pw.print("    ");
21507                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21508                        pw.print(": ");
21509                        pw.println(permission);
21510                    }
21511                }
21512            }
21513
21514            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21515                if (dumpState.onTitlePrinted()) pw.println();
21516                dumpDexoptStateLPr(pw, packageName);
21517            }
21518
21519            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21520                if (dumpState.onTitlePrinted()) pw.println();
21521                dumpCompilerStatsLPr(pw, packageName);
21522            }
21523
21524            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21525                if (dumpState.onTitlePrinted()) pw.println();
21526                mSettings.dumpReadMessagesLPr(pw, dumpState);
21527
21528                pw.println();
21529                pw.println("Package warning messages:");
21530                dumpCriticalInfo(pw, null);
21531            }
21532
21533            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21534                dumpCriticalInfo(pw, "msg,");
21535            }
21536        }
21537
21538        // PackageInstaller should be called outside of mPackages lock
21539        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21540            // XXX should handle packageName != null by dumping only install data that
21541            // the given package is involved with.
21542            if (dumpState.onTitlePrinted()) pw.println();
21543            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21544        }
21545    }
21546
21547    private void dumpProto(FileDescriptor fd) {
21548        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21549
21550        synchronized (mPackages) {
21551            final long requiredVerifierPackageToken =
21552                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21553            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21554            proto.write(
21555                    PackageServiceDumpProto.PackageShortProto.UID,
21556                    getPackageUid(
21557                            mRequiredVerifierPackage,
21558                            MATCH_DEBUG_TRIAGED_MISSING,
21559                            UserHandle.USER_SYSTEM));
21560            proto.end(requiredVerifierPackageToken);
21561
21562            if (mIntentFilterVerifierComponent != null) {
21563                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21564                final long verifierPackageToken =
21565                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21566                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21567                proto.write(
21568                        PackageServiceDumpProto.PackageShortProto.UID,
21569                        getPackageUid(
21570                                verifierPackageName,
21571                                MATCH_DEBUG_TRIAGED_MISSING,
21572                                UserHandle.USER_SYSTEM));
21573                proto.end(verifierPackageToken);
21574            }
21575
21576            dumpSharedLibrariesProto(proto);
21577            dumpFeaturesProto(proto);
21578            mSettings.dumpPackagesProto(proto);
21579            mSettings.dumpSharedUsersProto(proto);
21580            dumpCriticalInfo(proto);
21581        }
21582        proto.flush();
21583    }
21584
21585    private void dumpFeaturesProto(ProtoOutputStream proto) {
21586        synchronized (mAvailableFeatures) {
21587            final int count = mAvailableFeatures.size();
21588            for (int i = 0; i < count; i++) {
21589                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21590            }
21591        }
21592    }
21593
21594    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21595        final int count = mSharedLibraries.size();
21596        for (int i = 0; i < count; i++) {
21597            final String libName = mSharedLibraries.keyAt(i);
21598            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21599            if (versionedLib == null) {
21600                continue;
21601            }
21602            final int versionCount = versionedLib.size();
21603            for (int j = 0; j < versionCount; j++) {
21604                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21605                final long sharedLibraryToken =
21606                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21607                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21608                final boolean isJar = (libEntry.path != null);
21609                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21610                if (isJar) {
21611                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21612                } else {
21613                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21614                }
21615                proto.end(sharedLibraryToken);
21616            }
21617        }
21618    }
21619
21620    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21621        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21622        ipw.println();
21623        ipw.println("Dexopt state:");
21624        ipw.increaseIndent();
21625        Collection<PackageParser.Package> packages = null;
21626        if (packageName != null) {
21627            PackageParser.Package targetPackage = mPackages.get(packageName);
21628            if (targetPackage != null) {
21629                packages = Collections.singletonList(targetPackage);
21630            } else {
21631                ipw.println("Unable to find package: " + packageName);
21632                return;
21633            }
21634        } else {
21635            packages = mPackages.values();
21636        }
21637
21638        for (PackageParser.Package pkg : packages) {
21639            ipw.println("[" + pkg.packageName + "]");
21640            ipw.increaseIndent();
21641            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21642                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21643            ipw.decreaseIndent();
21644        }
21645    }
21646
21647    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21648        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21649        ipw.println();
21650        ipw.println("Compiler stats:");
21651        ipw.increaseIndent();
21652        Collection<PackageParser.Package> packages = null;
21653        if (packageName != null) {
21654            PackageParser.Package targetPackage = mPackages.get(packageName);
21655            if (targetPackage != null) {
21656                packages = Collections.singletonList(targetPackage);
21657            } else {
21658                ipw.println("Unable to find package: " + packageName);
21659                return;
21660            }
21661        } else {
21662            packages = mPackages.values();
21663        }
21664
21665        for (PackageParser.Package pkg : packages) {
21666            ipw.println("[" + pkg.packageName + "]");
21667            ipw.increaseIndent();
21668
21669            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21670            if (stats == null) {
21671                ipw.println("(No recorded stats)");
21672            } else {
21673                stats.dump(ipw);
21674            }
21675            ipw.decreaseIndent();
21676        }
21677    }
21678
21679    private String dumpDomainString(String packageName) {
21680        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21681                .getList();
21682        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21683
21684        ArraySet<String> result = new ArraySet<>();
21685        if (iviList.size() > 0) {
21686            for (IntentFilterVerificationInfo ivi : iviList) {
21687                for (String host : ivi.getDomains()) {
21688                    result.add(host);
21689                }
21690            }
21691        }
21692        if (filters != null && filters.size() > 0) {
21693            for (IntentFilter filter : filters) {
21694                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21695                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21696                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21697                    result.addAll(filter.getHostsList());
21698                }
21699            }
21700        }
21701
21702        StringBuilder sb = new StringBuilder(result.size() * 16);
21703        for (String domain : result) {
21704            if (sb.length() > 0) sb.append(" ");
21705            sb.append(domain);
21706        }
21707        return sb.toString();
21708    }
21709
21710    // ------- apps on sdcard specific code -------
21711    static final boolean DEBUG_SD_INSTALL = false;
21712
21713    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21714
21715    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21716
21717    private boolean mMediaMounted = false;
21718
21719    static String getEncryptKey() {
21720        try {
21721            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21722                    SD_ENCRYPTION_KEYSTORE_NAME);
21723            if (sdEncKey == null) {
21724                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21725                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21726                if (sdEncKey == null) {
21727                    Slog.e(TAG, "Failed to create encryption keys");
21728                    return null;
21729                }
21730            }
21731            return sdEncKey;
21732        } catch (NoSuchAlgorithmException nsae) {
21733            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21734            return null;
21735        } catch (IOException ioe) {
21736            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21737            return null;
21738        }
21739    }
21740
21741    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21742            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21743        final int size = infos.size();
21744        final String[] packageNames = new String[size];
21745        final int[] packageUids = new int[size];
21746        for (int i = 0; i < size; i++) {
21747            final ApplicationInfo info = infos.get(i);
21748            packageNames[i] = info.packageName;
21749            packageUids[i] = info.uid;
21750        }
21751        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21752                finishedReceiver);
21753    }
21754
21755    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21756            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21757        sendResourcesChangedBroadcast(mediaStatus, replacing,
21758                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21759    }
21760
21761    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21762            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21763        int size = pkgList.length;
21764        if (size > 0) {
21765            // Send broadcasts here
21766            Bundle extras = new Bundle();
21767            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21768            if (uidArr != null) {
21769                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21770            }
21771            if (replacing) {
21772                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21773            }
21774            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21775                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21776            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
21777        }
21778    }
21779
21780    private void loadPrivatePackages(final VolumeInfo vol) {
21781        mHandler.post(new Runnable() {
21782            @Override
21783            public void run() {
21784                loadPrivatePackagesInner(vol);
21785            }
21786        });
21787    }
21788
21789    private void loadPrivatePackagesInner(VolumeInfo vol) {
21790        final String volumeUuid = vol.fsUuid;
21791        if (TextUtils.isEmpty(volumeUuid)) {
21792            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21793            return;
21794        }
21795
21796        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21797        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21798        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21799
21800        final VersionInfo ver;
21801        final List<PackageSetting> packages;
21802        synchronized (mPackages) {
21803            ver = mSettings.findOrCreateVersion(volumeUuid);
21804            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21805        }
21806
21807        for (PackageSetting ps : packages) {
21808            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21809            synchronized (mInstallLock) {
21810                final PackageParser.Package pkg;
21811                try {
21812                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21813                    loaded.add(pkg.applicationInfo);
21814
21815                } catch (PackageManagerException e) {
21816                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21817                }
21818
21819                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21820                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21821                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21822                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21823                }
21824            }
21825        }
21826
21827        // Reconcile app data for all started/unlocked users
21828        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21829        final UserManager um = mContext.getSystemService(UserManager.class);
21830        UserManagerInternal umInternal = getUserManagerInternal();
21831        for (UserInfo user : um.getUsers()) {
21832            final int flags;
21833            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21834                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21835            } else if (umInternal.isUserRunning(user.id)) {
21836                flags = StorageManager.FLAG_STORAGE_DE;
21837            } else {
21838                continue;
21839            }
21840
21841            try {
21842                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21843                synchronized (mInstallLock) {
21844                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21845                }
21846            } catch (IllegalStateException e) {
21847                // Device was probably ejected, and we'll process that event momentarily
21848                Slog.w(TAG, "Failed to prepare storage: " + e);
21849            }
21850        }
21851
21852        synchronized (mPackages) {
21853            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
21854            if (sdkUpdated) {
21855                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21856                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21857            }
21858            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
21859                    mPermissionCallback);
21860
21861            // Yay, everything is now upgraded
21862            ver.forceCurrent();
21863
21864            mSettings.writeLPr();
21865        }
21866
21867        for (PackageFreezer freezer : freezers) {
21868            freezer.close();
21869        }
21870
21871        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21872        sendResourcesChangedBroadcast(true, false, loaded, null);
21873        mLoadedVolumes.add(vol.getId());
21874    }
21875
21876    private void unloadPrivatePackages(final VolumeInfo vol) {
21877        mHandler.post(new Runnable() {
21878            @Override
21879            public void run() {
21880                unloadPrivatePackagesInner(vol);
21881            }
21882        });
21883    }
21884
21885    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21886        final String volumeUuid = vol.fsUuid;
21887        if (TextUtils.isEmpty(volumeUuid)) {
21888            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21889            return;
21890        }
21891
21892        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21893        synchronized (mInstallLock) {
21894        synchronized (mPackages) {
21895            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21896            for (PackageSetting ps : packages) {
21897                if (ps.pkg == null) continue;
21898
21899                final ApplicationInfo info = ps.pkg.applicationInfo;
21900                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21901                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
21902
21903                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21904                        "unloadPrivatePackagesInner")) {
21905                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21906                            false, null)) {
21907                        unloaded.add(info);
21908                    } else {
21909                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21910                    }
21911                }
21912
21913                // Try very hard to release any references to this package
21914                // so we don't risk the system server being killed due to
21915                // open FDs
21916                AttributeCache.instance().removePackage(ps.name);
21917            }
21918
21919            mSettings.writeLPr();
21920        }
21921        }
21922
21923        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21924        sendResourcesChangedBroadcast(false, false, unloaded, null);
21925        mLoadedVolumes.remove(vol.getId());
21926
21927        // Try very hard to release any references to this path so we don't risk
21928        // the system server being killed due to open FDs
21929        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21930
21931        for (int i = 0; i < 3; i++) {
21932            System.gc();
21933            System.runFinalization();
21934        }
21935    }
21936
21937    private void assertPackageKnown(String volumeUuid, String packageName)
21938            throws PackageManagerException {
21939        synchronized (mPackages) {
21940            // Normalize package name to handle renamed packages
21941            packageName = normalizePackageNameLPr(packageName);
21942
21943            final PackageSetting ps = mSettings.mPackages.get(packageName);
21944            if (ps == null) {
21945                throw new PackageManagerException("Package " + packageName + " is unknown");
21946            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21947                throw new PackageManagerException(
21948                        "Package " + packageName + " found on unknown volume " + volumeUuid
21949                                + "; expected volume " + ps.volumeUuid);
21950            }
21951        }
21952    }
21953
21954    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21955            throws PackageManagerException {
21956        synchronized (mPackages) {
21957            // Normalize package name to handle renamed packages
21958            packageName = normalizePackageNameLPr(packageName);
21959
21960            final PackageSetting ps = mSettings.mPackages.get(packageName);
21961            if (ps == null) {
21962                throw new PackageManagerException("Package " + packageName + " is unknown");
21963            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21964                throw new PackageManagerException(
21965                        "Package " + packageName + " found on unknown volume " + volumeUuid
21966                                + "; expected volume " + ps.volumeUuid);
21967            } else if (!ps.getInstalled(userId)) {
21968                throw new PackageManagerException(
21969                        "Package " + packageName + " not installed for user " + userId);
21970            }
21971        }
21972    }
21973
21974    private List<String> collectAbsoluteCodePaths() {
21975        synchronized (mPackages) {
21976            List<String> codePaths = new ArrayList<>();
21977            final int packageCount = mSettings.mPackages.size();
21978            for (int i = 0; i < packageCount; i++) {
21979                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21980                codePaths.add(ps.codePath.getAbsolutePath());
21981            }
21982            return codePaths;
21983        }
21984    }
21985
21986    /**
21987     * Examine all apps present on given mounted volume, and destroy apps that
21988     * aren't expected, either due to uninstallation or reinstallation on
21989     * another volume.
21990     */
21991    private void reconcileApps(String volumeUuid) {
21992        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21993        List<File> filesToDelete = null;
21994
21995        final File[] files = FileUtils.listFilesOrEmpty(
21996                Environment.getDataAppDirectory(volumeUuid));
21997        for (File file : files) {
21998            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21999                    && !PackageInstallerService.isStageName(file.getName());
22000            if (!isPackage) {
22001                // Ignore entries which are not packages
22002                continue;
22003            }
22004
22005            String absolutePath = file.getAbsolutePath();
22006
22007            boolean pathValid = false;
22008            final int absoluteCodePathCount = absoluteCodePaths.size();
22009            for (int i = 0; i < absoluteCodePathCount; i++) {
22010                String absoluteCodePath = absoluteCodePaths.get(i);
22011                if (absolutePath.startsWith(absoluteCodePath)) {
22012                    pathValid = true;
22013                    break;
22014                }
22015            }
22016
22017            if (!pathValid) {
22018                if (filesToDelete == null) {
22019                    filesToDelete = new ArrayList<>();
22020                }
22021                filesToDelete.add(file);
22022            }
22023        }
22024
22025        if (filesToDelete != null) {
22026            final int fileToDeleteCount = filesToDelete.size();
22027            for (int i = 0; i < fileToDeleteCount; i++) {
22028                File fileToDelete = filesToDelete.get(i);
22029                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22030                synchronized (mInstallLock) {
22031                    removeCodePathLI(fileToDelete);
22032                }
22033            }
22034        }
22035    }
22036
22037    /**
22038     * Reconcile all app data for the given user.
22039     * <p>
22040     * Verifies that directories exist and that ownership and labeling is
22041     * correct for all installed apps on all mounted volumes.
22042     */
22043    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22044        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22045        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22046            final String volumeUuid = vol.getFsUuid();
22047            synchronized (mInstallLock) {
22048                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22049            }
22050        }
22051    }
22052
22053    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22054            boolean migrateAppData) {
22055        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22056    }
22057
22058    /**
22059     * Reconcile all app data on given mounted volume.
22060     * <p>
22061     * Destroys app data that isn't expected, either due to uninstallation or
22062     * reinstallation on another volume.
22063     * <p>
22064     * Verifies that directories exist and that ownership and labeling is
22065     * correct for all installed apps.
22066     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22067     */
22068    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22069            boolean migrateAppData, boolean onlyCoreApps) {
22070        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22071                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22072        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22073
22074        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22075        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22076
22077        // First look for stale data that doesn't belong, and check if things
22078        // have changed since we did our last restorecon
22079        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22080            if (StorageManager.isFileEncryptedNativeOrEmulated()
22081                    && !StorageManager.isUserKeyUnlocked(userId)) {
22082                throw new RuntimeException(
22083                        "Yikes, someone asked us to reconcile CE storage while " + userId
22084                                + " was still locked; this would have caused massive data loss!");
22085            }
22086
22087            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22088            for (File file : files) {
22089                final String packageName = file.getName();
22090                try {
22091                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22092                } catch (PackageManagerException e) {
22093                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22094                    try {
22095                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22096                                StorageManager.FLAG_STORAGE_CE, 0);
22097                    } catch (InstallerException e2) {
22098                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22099                    }
22100                }
22101            }
22102        }
22103        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22104            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22105            for (File file : files) {
22106                final String packageName = file.getName();
22107                try {
22108                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22109                } catch (PackageManagerException e) {
22110                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22111                    try {
22112                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22113                                StorageManager.FLAG_STORAGE_DE, 0);
22114                    } catch (InstallerException e2) {
22115                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22116                    }
22117                }
22118            }
22119        }
22120
22121        // Ensure that data directories are ready to roll for all packages
22122        // installed for this volume and user
22123        final List<PackageSetting> packages;
22124        synchronized (mPackages) {
22125            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22126        }
22127        int preparedCount = 0;
22128        for (PackageSetting ps : packages) {
22129            final String packageName = ps.name;
22130            if (ps.pkg == null) {
22131                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22132                // TODO: might be due to legacy ASEC apps; we should circle back
22133                // and reconcile again once they're scanned
22134                continue;
22135            }
22136            // Skip non-core apps if requested
22137            if (onlyCoreApps && !ps.pkg.coreApp) {
22138                result.add(packageName);
22139                continue;
22140            }
22141
22142            if (ps.getInstalled(userId)) {
22143                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22144                preparedCount++;
22145            }
22146        }
22147
22148        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22149        return result;
22150    }
22151
22152    /**
22153     * Prepare app data for the given app just after it was installed or
22154     * upgraded. This method carefully only touches users that it's installed
22155     * for, and it forces a restorecon to handle any seinfo changes.
22156     * <p>
22157     * Verifies that directories exist and that ownership and labeling is
22158     * correct for all installed apps. If there is an ownership mismatch, it
22159     * will try recovering system apps by wiping data; third-party app data is
22160     * left intact.
22161     * <p>
22162     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22163     */
22164    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22165        final PackageSetting ps;
22166        synchronized (mPackages) {
22167            ps = mSettings.mPackages.get(pkg.packageName);
22168            mSettings.writeKernelMappingLPr(ps);
22169        }
22170
22171        final UserManager um = mContext.getSystemService(UserManager.class);
22172        UserManagerInternal umInternal = getUserManagerInternal();
22173        for (UserInfo user : um.getUsers()) {
22174            final int flags;
22175            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22176                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22177            } else if (umInternal.isUserRunning(user.id)) {
22178                flags = StorageManager.FLAG_STORAGE_DE;
22179            } else {
22180                continue;
22181            }
22182
22183            if (ps.getInstalled(user.id)) {
22184                // TODO: when user data is locked, mark that we're still dirty
22185                prepareAppDataLIF(pkg, user.id, flags);
22186            }
22187        }
22188    }
22189
22190    /**
22191     * Prepare app data for the given app.
22192     * <p>
22193     * Verifies that directories exist and that ownership and labeling is
22194     * correct for all installed apps. If there is an ownership mismatch, this
22195     * will try recovering system apps by wiping data; third-party app data is
22196     * left intact.
22197     */
22198    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22199        if (pkg == null) {
22200            Slog.wtf(TAG, "Package was null!", new Throwable());
22201            return;
22202        }
22203        prepareAppDataLeafLIF(pkg, userId, flags);
22204        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22205        for (int i = 0; i < childCount; i++) {
22206            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22207        }
22208    }
22209
22210    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22211            boolean maybeMigrateAppData) {
22212        prepareAppDataLIF(pkg, userId, flags);
22213
22214        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22215            // We may have just shuffled around app data directories, so
22216            // prepare them one more time
22217            prepareAppDataLIF(pkg, userId, flags);
22218        }
22219    }
22220
22221    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22222        if (DEBUG_APP_DATA) {
22223            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22224                    + Integer.toHexString(flags));
22225        }
22226
22227        final String volumeUuid = pkg.volumeUuid;
22228        final String packageName = pkg.packageName;
22229        final ApplicationInfo app = pkg.applicationInfo;
22230        final int appId = UserHandle.getAppId(app.uid);
22231
22232        Preconditions.checkNotNull(app.seInfo);
22233
22234        long ceDataInode = -1;
22235        try {
22236            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22237                    appId, app.seInfo, app.targetSdkVersion);
22238        } catch (InstallerException e) {
22239            if (app.isSystemApp()) {
22240                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22241                        + ", but trying to recover: " + e);
22242                destroyAppDataLeafLIF(pkg, userId, flags);
22243                try {
22244                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22245                            appId, app.seInfo, app.targetSdkVersion);
22246                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22247                } catch (InstallerException e2) {
22248                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22249                }
22250            } else {
22251                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22252            }
22253        }
22254        // Prepare the application profiles.
22255        mArtManagerService.prepareAppProfiles(pkg, userId);
22256
22257        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22258            // TODO: mark this structure as dirty so we persist it!
22259            synchronized (mPackages) {
22260                final PackageSetting ps = mSettings.mPackages.get(packageName);
22261                if (ps != null) {
22262                    ps.setCeDataInode(ceDataInode, userId);
22263                }
22264            }
22265        }
22266
22267        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22268    }
22269
22270    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22271        if (pkg == null) {
22272            Slog.wtf(TAG, "Package was null!", new Throwable());
22273            return;
22274        }
22275        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22276        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22277        for (int i = 0; i < childCount; i++) {
22278            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22279        }
22280    }
22281
22282    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22283        final String volumeUuid = pkg.volumeUuid;
22284        final String packageName = pkg.packageName;
22285        final ApplicationInfo app = pkg.applicationInfo;
22286
22287        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22288            // Create a native library symlink only if we have native libraries
22289            // and if the native libraries are 32 bit libraries. We do not provide
22290            // this symlink for 64 bit libraries.
22291            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22292                final String nativeLibPath = app.nativeLibraryDir;
22293                try {
22294                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22295                            nativeLibPath, userId);
22296                } catch (InstallerException e) {
22297                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22298                }
22299            }
22300        }
22301    }
22302
22303    /**
22304     * For system apps on non-FBE devices, this method migrates any existing
22305     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22306     * requested by the app.
22307     */
22308    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22309        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
22310                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22311            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22312                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22313            try {
22314                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22315                        storageTarget);
22316            } catch (InstallerException e) {
22317                logCriticalInfo(Log.WARN,
22318                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22319            }
22320            return true;
22321        } else {
22322            return false;
22323        }
22324    }
22325
22326    public PackageFreezer freezePackage(String packageName, String killReason) {
22327        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22328    }
22329
22330    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22331        return new PackageFreezer(packageName, userId, killReason);
22332    }
22333
22334    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22335            String killReason) {
22336        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22337    }
22338
22339    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22340            String killReason) {
22341        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22342            return new PackageFreezer();
22343        } else {
22344            return freezePackage(packageName, userId, killReason);
22345        }
22346    }
22347
22348    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22349            String killReason) {
22350        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22351    }
22352
22353    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22354            String killReason) {
22355        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22356            return new PackageFreezer();
22357        } else {
22358            return freezePackage(packageName, userId, killReason);
22359        }
22360    }
22361
22362    /**
22363     * Class that freezes and kills the given package upon creation, and
22364     * unfreezes it upon closing. This is typically used when doing surgery on
22365     * app code/data to prevent the app from running while you're working.
22366     */
22367    private class PackageFreezer implements AutoCloseable {
22368        private final String mPackageName;
22369        private final PackageFreezer[] mChildren;
22370
22371        private final boolean mWeFroze;
22372
22373        private final AtomicBoolean mClosed = new AtomicBoolean();
22374        private final CloseGuard mCloseGuard = CloseGuard.get();
22375
22376        /**
22377         * Create and return a stub freezer that doesn't actually do anything,
22378         * typically used when someone requested
22379         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22380         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22381         */
22382        public PackageFreezer() {
22383            mPackageName = null;
22384            mChildren = null;
22385            mWeFroze = false;
22386            mCloseGuard.open("close");
22387        }
22388
22389        public PackageFreezer(String packageName, int userId, String killReason) {
22390            synchronized (mPackages) {
22391                mPackageName = packageName;
22392                mWeFroze = mFrozenPackages.add(mPackageName);
22393
22394                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22395                if (ps != null) {
22396                    killApplication(ps.name, ps.appId, userId, killReason);
22397                }
22398
22399                final PackageParser.Package p = mPackages.get(packageName);
22400                if (p != null && p.childPackages != null) {
22401                    final int N = p.childPackages.size();
22402                    mChildren = new PackageFreezer[N];
22403                    for (int i = 0; i < N; i++) {
22404                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22405                                userId, killReason);
22406                    }
22407                } else {
22408                    mChildren = null;
22409                }
22410            }
22411            mCloseGuard.open("close");
22412        }
22413
22414        @Override
22415        protected void finalize() throws Throwable {
22416            try {
22417                if (mCloseGuard != null) {
22418                    mCloseGuard.warnIfOpen();
22419                }
22420
22421                close();
22422            } finally {
22423                super.finalize();
22424            }
22425        }
22426
22427        @Override
22428        public void close() {
22429            mCloseGuard.close();
22430            if (mClosed.compareAndSet(false, true)) {
22431                synchronized (mPackages) {
22432                    if (mWeFroze) {
22433                        mFrozenPackages.remove(mPackageName);
22434                    }
22435
22436                    if (mChildren != null) {
22437                        for (PackageFreezer freezer : mChildren) {
22438                            freezer.close();
22439                        }
22440                    }
22441                }
22442            }
22443        }
22444    }
22445
22446    /**
22447     * Verify that given package is currently frozen.
22448     */
22449    private void checkPackageFrozen(String packageName) {
22450        synchronized (mPackages) {
22451            if (!mFrozenPackages.contains(packageName)) {
22452                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22453            }
22454        }
22455    }
22456
22457    @Override
22458    public int movePackage(final String packageName, final String volumeUuid) {
22459        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22460
22461        final int callingUid = Binder.getCallingUid();
22462        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22463        final int moveId = mNextMoveId.getAndIncrement();
22464        mHandler.post(new Runnable() {
22465            @Override
22466            public void run() {
22467                try {
22468                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22469                } catch (PackageManagerException e) {
22470                    Slog.w(TAG, "Failed to move " + packageName, e);
22471                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22472                }
22473            }
22474        });
22475        return moveId;
22476    }
22477
22478    private void movePackageInternal(final String packageName, final String volumeUuid,
22479            final int moveId, final int callingUid, UserHandle user)
22480                    throws PackageManagerException {
22481        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22482        final PackageManager pm = mContext.getPackageManager();
22483
22484        final boolean currentAsec;
22485        final String currentVolumeUuid;
22486        final File codeFile;
22487        final String installerPackageName;
22488        final String packageAbiOverride;
22489        final int appId;
22490        final String seinfo;
22491        final String label;
22492        final int targetSdkVersion;
22493        final PackageFreezer freezer;
22494        final int[] installedUserIds;
22495
22496        // reader
22497        synchronized (mPackages) {
22498            final PackageParser.Package pkg = mPackages.get(packageName);
22499            final PackageSetting ps = mSettings.mPackages.get(packageName);
22500            if (pkg == null
22501                    || ps == null
22502                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22503                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22504            }
22505            if (pkg.applicationInfo.isSystemApp()) {
22506                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22507                        "Cannot move system application");
22508            }
22509
22510            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22511            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22512                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22513            if (isInternalStorage && !allow3rdPartyOnInternal) {
22514                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22515                        "3rd party apps are not allowed on internal storage");
22516            }
22517
22518            if (pkg.applicationInfo.isExternalAsec()) {
22519                currentAsec = true;
22520                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22521            } else if (pkg.applicationInfo.isForwardLocked()) {
22522                currentAsec = true;
22523                currentVolumeUuid = "forward_locked";
22524            } else {
22525                currentAsec = false;
22526                currentVolumeUuid = ps.volumeUuid;
22527
22528                final File probe = new File(pkg.codePath);
22529                final File probeOat = new File(probe, "oat");
22530                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22531                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22532                            "Move only supported for modern cluster style installs");
22533                }
22534            }
22535
22536            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22537                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22538                        "Package already moved to " + volumeUuid);
22539            }
22540            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22541                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22542                        "Device admin cannot be moved");
22543            }
22544
22545            if (mFrozenPackages.contains(packageName)) {
22546                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22547                        "Failed to move already frozen package");
22548            }
22549
22550            codeFile = new File(pkg.codePath);
22551            installerPackageName = ps.installerPackageName;
22552            packageAbiOverride = ps.cpuAbiOverrideString;
22553            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22554            seinfo = pkg.applicationInfo.seInfo;
22555            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22556            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22557            freezer = freezePackage(packageName, "movePackageInternal");
22558            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22559        }
22560
22561        final Bundle extras = new Bundle();
22562        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22563        extras.putString(Intent.EXTRA_TITLE, label);
22564        mMoveCallbacks.notifyCreated(moveId, extras);
22565
22566        int installFlags;
22567        final boolean moveCompleteApp;
22568        final File measurePath;
22569
22570        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22571            installFlags = INSTALL_INTERNAL;
22572            moveCompleteApp = !currentAsec;
22573            measurePath = Environment.getDataAppDirectory(volumeUuid);
22574        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22575            installFlags = INSTALL_EXTERNAL;
22576            moveCompleteApp = false;
22577            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22578        } else {
22579            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22580            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22581                    || !volume.isMountedWritable()) {
22582                freezer.close();
22583                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22584                        "Move location not mounted private volume");
22585            }
22586
22587            Preconditions.checkState(!currentAsec);
22588
22589            installFlags = INSTALL_INTERNAL;
22590            moveCompleteApp = true;
22591            measurePath = Environment.getDataAppDirectory(volumeUuid);
22592        }
22593
22594        // If we're moving app data around, we need all the users unlocked
22595        if (moveCompleteApp) {
22596            for (int userId : installedUserIds) {
22597                if (StorageManager.isFileEncryptedNativeOrEmulated()
22598                        && !StorageManager.isUserKeyUnlocked(userId)) {
22599                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22600                            "User " + userId + " must be unlocked");
22601                }
22602            }
22603        }
22604
22605        final PackageStats stats = new PackageStats(null, -1);
22606        synchronized (mInstaller) {
22607            for (int userId : installedUserIds) {
22608                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22609                    freezer.close();
22610                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22611                            "Failed to measure package size");
22612                }
22613            }
22614        }
22615
22616        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22617                + stats.dataSize);
22618
22619        final long startFreeBytes = measurePath.getUsableSpace();
22620        final long sizeBytes;
22621        if (moveCompleteApp) {
22622            sizeBytes = stats.codeSize + stats.dataSize;
22623        } else {
22624            sizeBytes = stats.codeSize;
22625        }
22626
22627        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22628            freezer.close();
22629            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22630                    "Not enough free space to move");
22631        }
22632
22633        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22634
22635        final CountDownLatch installedLatch = new CountDownLatch(1);
22636        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22637            @Override
22638            public void onUserActionRequired(Intent intent) throws RemoteException {
22639                throw new IllegalStateException();
22640            }
22641
22642            @Override
22643            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22644                    Bundle extras) throws RemoteException {
22645                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22646                        + PackageManager.installStatusToString(returnCode, msg));
22647
22648                installedLatch.countDown();
22649                freezer.close();
22650
22651                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22652                switch (status) {
22653                    case PackageInstaller.STATUS_SUCCESS:
22654                        mMoveCallbacks.notifyStatusChanged(moveId,
22655                                PackageManager.MOVE_SUCCEEDED);
22656                        break;
22657                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22658                        mMoveCallbacks.notifyStatusChanged(moveId,
22659                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22660                        break;
22661                    default:
22662                        mMoveCallbacks.notifyStatusChanged(moveId,
22663                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22664                        break;
22665                }
22666            }
22667        };
22668
22669        final MoveInfo move;
22670        if (moveCompleteApp) {
22671            // Kick off a thread to report progress estimates
22672            new Thread() {
22673                @Override
22674                public void run() {
22675                    while (true) {
22676                        try {
22677                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22678                                break;
22679                            }
22680                        } catch (InterruptedException ignored) {
22681                        }
22682
22683                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22684                        final int progress = 10 + (int) MathUtils.constrain(
22685                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22686                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22687                    }
22688                }
22689            }.start();
22690
22691            final String dataAppName = codeFile.getName();
22692            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22693                    dataAppName, appId, seinfo, targetSdkVersion);
22694        } else {
22695            move = null;
22696        }
22697
22698        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22699
22700        final Message msg = mHandler.obtainMessage(INIT_COPY);
22701        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22702        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22703                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22704                packageAbiOverride, null /*grantedPermissions*/,
22705                PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
22706        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22707        msg.obj = params;
22708
22709        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22710                System.identityHashCode(msg.obj));
22711        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22712                System.identityHashCode(msg.obj));
22713
22714        mHandler.sendMessage(msg);
22715    }
22716
22717    @Override
22718    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22719        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22720
22721        final int realMoveId = mNextMoveId.getAndIncrement();
22722        final Bundle extras = new Bundle();
22723        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22724        mMoveCallbacks.notifyCreated(realMoveId, extras);
22725
22726        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22727            @Override
22728            public void onCreated(int moveId, Bundle extras) {
22729                // Ignored
22730            }
22731
22732            @Override
22733            public void onStatusChanged(int moveId, int status, long estMillis) {
22734                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22735            }
22736        };
22737
22738        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22739        storage.setPrimaryStorageUuid(volumeUuid, callback);
22740        return realMoveId;
22741    }
22742
22743    @Override
22744    public int getMoveStatus(int moveId) {
22745        mContext.enforceCallingOrSelfPermission(
22746                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22747        return mMoveCallbacks.mLastStatus.get(moveId);
22748    }
22749
22750    @Override
22751    public void registerMoveCallback(IPackageMoveObserver callback) {
22752        mContext.enforceCallingOrSelfPermission(
22753                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22754        mMoveCallbacks.register(callback);
22755    }
22756
22757    @Override
22758    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22759        mContext.enforceCallingOrSelfPermission(
22760                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22761        mMoveCallbacks.unregister(callback);
22762    }
22763
22764    @Override
22765    public boolean setInstallLocation(int loc) {
22766        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22767                null);
22768        if (getInstallLocation() == loc) {
22769            return true;
22770        }
22771        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22772                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22773            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22774                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22775            return true;
22776        }
22777        return false;
22778   }
22779
22780    @Override
22781    public int getInstallLocation() {
22782        // allow instant app access
22783        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22784                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22785                PackageHelper.APP_INSTALL_AUTO);
22786    }
22787
22788    /** Called by UserManagerService */
22789    void cleanUpUser(UserManagerService userManager, int userHandle) {
22790        synchronized (mPackages) {
22791            mDirtyUsers.remove(userHandle);
22792            mUserNeedsBadging.delete(userHandle);
22793            mSettings.removeUserLPw(userHandle);
22794            mPendingBroadcasts.remove(userHandle);
22795            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22796            removeUnusedPackagesLPw(userManager, userHandle);
22797        }
22798    }
22799
22800    /**
22801     * We're removing userHandle and would like to remove any downloaded packages
22802     * that are no longer in use by any other user.
22803     * @param userHandle the user being removed
22804     */
22805    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22806        final boolean DEBUG_CLEAN_APKS = false;
22807        int [] users = userManager.getUserIds();
22808        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22809        while (psit.hasNext()) {
22810            PackageSetting ps = psit.next();
22811            if (ps.pkg == null) {
22812                continue;
22813            }
22814            final String packageName = ps.pkg.packageName;
22815            // Skip over if system app
22816            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22817                continue;
22818            }
22819            if (DEBUG_CLEAN_APKS) {
22820                Slog.i(TAG, "Checking package " + packageName);
22821            }
22822            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22823            if (keep) {
22824                if (DEBUG_CLEAN_APKS) {
22825                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22826                }
22827            } else {
22828                for (int i = 0; i < users.length; i++) {
22829                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22830                        keep = true;
22831                        if (DEBUG_CLEAN_APKS) {
22832                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22833                                    + users[i]);
22834                        }
22835                        break;
22836                    }
22837                }
22838            }
22839            if (!keep) {
22840                if (DEBUG_CLEAN_APKS) {
22841                    Slog.i(TAG, "  Removing package " + packageName);
22842                }
22843                mHandler.post(new Runnable() {
22844                    public void run() {
22845                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22846                                userHandle, 0);
22847                    } //end run
22848                });
22849            }
22850        }
22851    }
22852
22853    /** Called by UserManagerService */
22854    void createNewUser(int userId, String[] disallowedPackages) {
22855        synchronized (mInstallLock) {
22856            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22857        }
22858        synchronized (mPackages) {
22859            scheduleWritePackageRestrictionsLocked(userId);
22860            scheduleWritePackageListLocked(userId);
22861            applyFactoryDefaultBrowserLPw(userId);
22862            primeDomainVerificationsLPw(userId);
22863        }
22864    }
22865
22866    void onNewUserCreated(final int userId) {
22867        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22868        synchronized(mPackages) {
22869            // If permission review for legacy apps is required, we represent
22870            // dagerous permissions for such apps as always granted runtime
22871            // permissions to keep per user flag state whether review is needed.
22872            // Hence, if a new user is added we have to propagate dangerous
22873            // permission grants for these legacy apps.
22874            if (mSettings.mPermissions.mPermissionReviewRequired) {
22875// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
22876                mPermissionManager.updateAllPermissions(
22877                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
22878                        mPermissionCallback);
22879            }
22880        }
22881    }
22882
22883    @Override
22884    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22885        mContext.enforceCallingOrSelfPermission(
22886                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22887                "Only package verification agents can read the verifier device identity");
22888
22889        synchronized (mPackages) {
22890            return mSettings.getVerifierDeviceIdentityLPw();
22891        }
22892    }
22893
22894    @Override
22895    public void setPermissionEnforced(String permission, boolean enforced) {
22896        // TODO: Now that we no longer change GID for storage, this should to away.
22897        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22898                "setPermissionEnforced");
22899        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22900            synchronized (mPackages) {
22901                if (mSettings.mReadExternalStorageEnforced == null
22902                        || mSettings.mReadExternalStorageEnforced != enforced) {
22903                    mSettings.mReadExternalStorageEnforced =
22904                            enforced ? Boolean.TRUE : Boolean.FALSE;
22905                    mSettings.writeLPr();
22906                }
22907            }
22908            // kill any non-foreground processes so we restart them and
22909            // grant/revoke the GID.
22910            final IActivityManager am = ActivityManager.getService();
22911            if (am != null) {
22912                final long token = Binder.clearCallingIdentity();
22913                try {
22914                    am.killProcessesBelowForeground("setPermissionEnforcement");
22915                } catch (RemoteException e) {
22916                } finally {
22917                    Binder.restoreCallingIdentity(token);
22918                }
22919            }
22920        } else {
22921            throw new IllegalArgumentException("No selective enforcement for " + permission);
22922        }
22923    }
22924
22925    @Override
22926    @Deprecated
22927    public boolean isPermissionEnforced(String permission) {
22928        // allow instant applications
22929        return true;
22930    }
22931
22932    @Override
22933    public boolean isStorageLow() {
22934        // allow instant applications
22935        final long token = Binder.clearCallingIdentity();
22936        try {
22937            final DeviceStorageMonitorInternal
22938                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22939            if (dsm != null) {
22940                return dsm.isMemoryLow();
22941            } else {
22942                return false;
22943            }
22944        } finally {
22945            Binder.restoreCallingIdentity(token);
22946        }
22947    }
22948
22949    @Override
22950    public IPackageInstaller getPackageInstaller() {
22951        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
22952            return null;
22953        }
22954        return mInstallerService;
22955    }
22956
22957    @Override
22958    public IArtManager getArtManager() {
22959        return mArtManagerService;
22960    }
22961
22962    private boolean userNeedsBadging(int userId) {
22963        int index = mUserNeedsBadging.indexOfKey(userId);
22964        if (index < 0) {
22965            final UserInfo userInfo;
22966            final long token = Binder.clearCallingIdentity();
22967            try {
22968                userInfo = sUserManager.getUserInfo(userId);
22969            } finally {
22970                Binder.restoreCallingIdentity(token);
22971            }
22972            final boolean b;
22973            if (userInfo != null && userInfo.isManagedProfile()) {
22974                b = true;
22975            } else {
22976                b = false;
22977            }
22978            mUserNeedsBadging.put(userId, b);
22979            return b;
22980        }
22981        return mUserNeedsBadging.valueAt(index);
22982    }
22983
22984    @Override
22985    public KeySet getKeySetByAlias(String packageName, String alias) {
22986        if (packageName == null || alias == null) {
22987            return null;
22988        }
22989        synchronized(mPackages) {
22990            final PackageParser.Package pkg = mPackages.get(packageName);
22991            if (pkg == null) {
22992                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22993                throw new IllegalArgumentException("Unknown package: " + packageName);
22994            }
22995            final PackageSetting ps = (PackageSetting) pkg.mExtras;
22996            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
22997                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
22998                throw new IllegalArgumentException("Unknown package: " + packageName);
22999            }
23000            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23001            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23002        }
23003    }
23004
23005    @Override
23006    public KeySet getSigningKeySet(String packageName) {
23007        if (packageName == null) {
23008            return null;
23009        }
23010        synchronized(mPackages) {
23011            final int callingUid = Binder.getCallingUid();
23012            final int callingUserId = UserHandle.getUserId(callingUid);
23013            final PackageParser.Package pkg = mPackages.get(packageName);
23014            if (pkg == null) {
23015                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23016                throw new IllegalArgumentException("Unknown package: " + packageName);
23017            }
23018            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23019            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23020                // filter and pretend the package doesn't exist
23021                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23022                        + ", uid:" + callingUid);
23023                throw new IllegalArgumentException("Unknown package: " + packageName);
23024            }
23025            if (pkg.applicationInfo.uid != callingUid
23026                    && Process.SYSTEM_UID != callingUid) {
23027                throw new SecurityException("May not access signing KeySet of other apps.");
23028            }
23029            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23030            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23031        }
23032    }
23033
23034    @Override
23035    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23036        final int callingUid = Binder.getCallingUid();
23037        if (getInstantAppPackageName(callingUid) != null) {
23038            return false;
23039        }
23040        if (packageName == null || ks == null) {
23041            return false;
23042        }
23043        synchronized(mPackages) {
23044            final PackageParser.Package pkg = mPackages.get(packageName);
23045            if (pkg == null
23046                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23047                            UserHandle.getUserId(callingUid))) {
23048                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23049                throw new IllegalArgumentException("Unknown package: " + packageName);
23050            }
23051            IBinder ksh = ks.getToken();
23052            if (ksh instanceof KeySetHandle) {
23053                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23054                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23055            }
23056            return false;
23057        }
23058    }
23059
23060    @Override
23061    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23062        final int callingUid = Binder.getCallingUid();
23063        if (getInstantAppPackageName(callingUid) != null) {
23064            return false;
23065        }
23066        if (packageName == null || ks == null) {
23067            return false;
23068        }
23069        synchronized(mPackages) {
23070            final PackageParser.Package pkg = mPackages.get(packageName);
23071            if (pkg == null
23072                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23073                            UserHandle.getUserId(callingUid))) {
23074                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23075                throw new IllegalArgumentException("Unknown package: " + packageName);
23076            }
23077            IBinder ksh = ks.getToken();
23078            if (ksh instanceof KeySetHandle) {
23079                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23080                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23081            }
23082            return false;
23083        }
23084    }
23085
23086    private void deletePackageIfUnusedLPr(final String packageName) {
23087        PackageSetting ps = mSettings.mPackages.get(packageName);
23088        if (ps == null) {
23089            return;
23090        }
23091        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23092            // TODO Implement atomic delete if package is unused
23093            // It is currently possible that the package will be deleted even if it is installed
23094            // after this method returns.
23095            mHandler.post(new Runnable() {
23096                public void run() {
23097                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23098                            0, PackageManager.DELETE_ALL_USERS);
23099                }
23100            });
23101        }
23102    }
23103
23104    /**
23105     * Check and throw if the given before/after packages would be considered a
23106     * downgrade.
23107     */
23108    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23109            throws PackageManagerException {
23110        if (after.getLongVersionCode() < before.getLongVersionCode()) {
23111            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23112                    "Update version code " + after.versionCode + " is older than current "
23113                    + before.getLongVersionCode());
23114        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
23115            if (after.baseRevisionCode < before.baseRevisionCode) {
23116                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23117                        "Update base revision code " + after.baseRevisionCode
23118                        + " is older than current " + before.baseRevisionCode);
23119            }
23120
23121            if (!ArrayUtils.isEmpty(after.splitNames)) {
23122                for (int i = 0; i < after.splitNames.length; i++) {
23123                    final String splitName = after.splitNames[i];
23124                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23125                    if (j != -1) {
23126                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23127                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23128                                    "Update split " + splitName + " revision code "
23129                                    + after.splitRevisionCodes[i] + " is older than current "
23130                                    + before.splitRevisionCodes[j]);
23131                        }
23132                    }
23133                }
23134            }
23135        }
23136    }
23137
23138    private static class MoveCallbacks extends Handler {
23139        private static final int MSG_CREATED = 1;
23140        private static final int MSG_STATUS_CHANGED = 2;
23141
23142        private final RemoteCallbackList<IPackageMoveObserver>
23143                mCallbacks = new RemoteCallbackList<>();
23144
23145        private final SparseIntArray mLastStatus = new SparseIntArray();
23146
23147        public MoveCallbacks(Looper looper) {
23148            super(looper);
23149        }
23150
23151        public void register(IPackageMoveObserver callback) {
23152            mCallbacks.register(callback);
23153        }
23154
23155        public void unregister(IPackageMoveObserver callback) {
23156            mCallbacks.unregister(callback);
23157        }
23158
23159        @Override
23160        public void handleMessage(Message msg) {
23161            final SomeArgs args = (SomeArgs) msg.obj;
23162            final int n = mCallbacks.beginBroadcast();
23163            for (int i = 0; i < n; i++) {
23164                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23165                try {
23166                    invokeCallback(callback, msg.what, args);
23167                } catch (RemoteException ignored) {
23168                }
23169            }
23170            mCallbacks.finishBroadcast();
23171            args.recycle();
23172        }
23173
23174        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23175                throws RemoteException {
23176            switch (what) {
23177                case MSG_CREATED: {
23178                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23179                    break;
23180                }
23181                case MSG_STATUS_CHANGED: {
23182                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23183                    break;
23184                }
23185            }
23186        }
23187
23188        private void notifyCreated(int moveId, Bundle extras) {
23189            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23190
23191            final SomeArgs args = SomeArgs.obtain();
23192            args.argi1 = moveId;
23193            args.arg2 = extras;
23194            obtainMessage(MSG_CREATED, args).sendToTarget();
23195        }
23196
23197        private void notifyStatusChanged(int moveId, int status) {
23198            notifyStatusChanged(moveId, status, -1);
23199        }
23200
23201        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23202            Slog.v(TAG, "Move " + moveId + " status " + status);
23203
23204            final SomeArgs args = SomeArgs.obtain();
23205            args.argi1 = moveId;
23206            args.argi2 = status;
23207            args.arg3 = estMillis;
23208            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23209
23210            synchronized (mLastStatus) {
23211                mLastStatus.put(moveId, status);
23212            }
23213        }
23214    }
23215
23216    private final static class OnPermissionChangeListeners extends Handler {
23217        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23218
23219        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23220                new RemoteCallbackList<>();
23221
23222        public OnPermissionChangeListeners(Looper looper) {
23223            super(looper);
23224        }
23225
23226        @Override
23227        public void handleMessage(Message msg) {
23228            switch (msg.what) {
23229                case MSG_ON_PERMISSIONS_CHANGED: {
23230                    final int uid = msg.arg1;
23231                    handleOnPermissionsChanged(uid);
23232                } break;
23233            }
23234        }
23235
23236        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23237            mPermissionListeners.register(listener);
23238
23239        }
23240
23241        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23242            mPermissionListeners.unregister(listener);
23243        }
23244
23245        public void onPermissionsChanged(int uid) {
23246            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23247                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23248            }
23249        }
23250
23251        private void handleOnPermissionsChanged(int uid) {
23252            final int count = mPermissionListeners.beginBroadcast();
23253            try {
23254                for (int i = 0; i < count; i++) {
23255                    IOnPermissionsChangeListener callback = mPermissionListeners
23256                            .getBroadcastItem(i);
23257                    try {
23258                        callback.onPermissionsChanged(uid);
23259                    } catch (RemoteException e) {
23260                        Log.e(TAG, "Permission listener is dead", e);
23261                    }
23262                }
23263            } finally {
23264                mPermissionListeners.finishBroadcast();
23265            }
23266        }
23267    }
23268
23269    private class PackageManagerNative extends IPackageManagerNative.Stub {
23270        @Override
23271        public String[] getNamesForUids(int[] uids) throws RemoteException {
23272            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23273            // massage results so they can be parsed by the native binder
23274            for (int i = results.length - 1; i >= 0; --i) {
23275                if (results[i] == null) {
23276                    results[i] = "";
23277                }
23278            }
23279            return results;
23280        }
23281
23282        // NB: this differentiates between preloads and sideloads
23283        @Override
23284        public String getInstallerForPackage(String packageName) throws RemoteException {
23285            final String installerName = getInstallerPackageName(packageName);
23286            if (!TextUtils.isEmpty(installerName)) {
23287                return installerName;
23288            }
23289            // differentiate between preload and sideload
23290            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23291            ApplicationInfo appInfo = getApplicationInfo(packageName,
23292                                    /*flags*/ 0,
23293                                    /*userId*/ callingUser);
23294            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23295                return "preload";
23296            }
23297            return "";
23298        }
23299
23300        @Override
23301        public long getVersionCodeForPackage(String packageName) throws RemoteException {
23302            try {
23303                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23304                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23305                if (pInfo != null) {
23306                    return pInfo.getLongVersionCode();
23307                }
23308            } catch (Exception e) {
23309            }
23310            return 0;
23311        }
23312    }
23313
23314    private class PackageManagerInternalImpl extends PackageManagerInternal {
23315        @Override
23316        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23317                int flagValues, int userId) {
23318            PackageManagerService.this.updatePermissionFlags(
23319                    permName, packageName, flagMask, flagValues, userId);
23320        }
23321
23322        @Override
23323        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23324            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23325        }
23326
23327        @Override
23328        public boolean isInstantApp(String packageName, int userId) {
23329            return PackageManagerService.this.isInstantApp(packageName, userId);
23330        }
23331
23332        @Override
23333        public String getInstantAppPackageName(int uid) {
23334            return PackageManagerService.this.getInstantAppPackageName(uid);
23335        }
23336
23337        @Override
23338        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23339            synchronized (mPackages) {
23340                return PackageManagerService.this.filterAppAccessLPr(
23341                        (PackageSetting) pkg.mExtras, callingUid, userId);
23342            }
23343        }
23344
23345        @Override
23346        public PackageParser.Package getPackage(String packageName) {
23347            synchronized (mPackages) {
23348                packageName = resolveInternalPackageNameLPr(
23349                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23350                return mPackages.get(packageName);
23351            }
23352        }
23353
23354        @Override
23355        public PackageList getPackageList(PackageListObserver observer) {
23356            synchronized (mPackages) {
23357                final int N = mPackages.size();
23358                final ArrayList<String> list = new ArrayList<>(N);
23359                for (int i = 0; i < N; i++) {
23360                    list.add(mPackages.keyAt(i));
23361                }
23362                final PackageList packageList = new PackageList(list, observer);
23363                if (observer != null) {
23364                    mPackageListObservers.add(packageList);
23365                }
23366                return packageList;
23367            }
23368        }
23369
23370        @Override
23371        public void removePackageListObserver(PackageListObserver observer) {
23372            synchronized (mPackages) {
23373                mPackageListObservers.remove(observer);
23374            }
23375        }
23376
23377        @Override
23378        public PackageParser.Package getDisabledPackage(String packageName) {
23379            synchronized (mPackages) {
23380                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23381                return (ps != null) ? ps.pkg : null;
23382            }
23383        }
23384
23385        @Override
23386        public String getKnownPackageName(int knownPackage, int userId) {
23387            switch(knownPackage) {
23388                case PackageManagerInternal.PACKAGE_BROWSER:
23389                    return getDefaultBrowserPackageName(userId);
23390                case PackageManagerInternal.PACKAGE_INSTALLER:
23391                    return mRequiredInstallerPackage;
23392                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23393                    return mSetupWizardPackage;
23394                case PackageManagerInternal.PACKAGE_SYSTEM:
23395                    return "android";
23396                case PackageManagerInternal.PACKAGE_VERIFIER:
23397                    return mRequiredVerifierPackage;
23398            }
23399            return null;
23400        }
23401
23402        @Override
23403        public boolean isResolveActivityComponent(ComponentInfo component) {
23404            return mResolveActivity.packageName.equals(component.packageName)
23405                    && mResolveActivity.name.equals(component.name);
23406        }
23407
23408        @Override
23409        public void setLocationPackagesProvider(PackagesProvider provider) {
23410            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23411        }
23412
23413        @Override
23414        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23415            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23416        }
23417
23418        @Override
23419        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23420            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23421        }
23422
23423        @Override
23424        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23425            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23426        }
23427
23428        @Override
23429        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23430            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23431        }
23432
23433        @Override
23434        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23435            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23436        }
23437
23438        @Override
23439        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23440            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23441        }
23442
23443        @Override
23444        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23445            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23446        }
23447
23448        @Override
23449        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23450            synchronized (mPackages) {
23451                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23452            }
23453            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23454        }
23455
23456        @Override
23457        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23458            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23459                    packageName, userId);
23460        }
23461
23462        @Override
23463        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23464            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23465                    packageName, userId);
23466        }
23467
23468        @Override
23469        public void setKeepUninstalledPackages(final List<String> packageList) {
23470            Preconditions.checkNotNull(packageList);
23471            List<String> removedFromList = null;
23472            synchronized (mPackages) {
23473                if (mKeepUninstalledPackages != null) {
23474                    final int packagesCount = mKeepUninstalledPackages.size();
23475                    for (int i = 0; i < packagesCount; i++) {
23476                        String oldPackage = mKeepUninstalledPackages.get(i);
23477                        if (packageList != null && packageList.contains(oldPackage)) {
23478                            continue;
23479                        }
23480                        if (removedFromList == null) {
23481                            removedFromList = new ArrayList<>();
23482                        }
23483                        removedFromList.add(oldPackage);
23484                    }
23485                }
23486                mKeepUninstalledPackages = new ArrayList<>(packageList);
23487                if (removedFromList != null) {
23488                    final int removedCount = removedFromList.size();
23489                    for (int i = 0; i < removedCount; i++) {
23490                        deletePackageIfUnusedLPr(removedFromList.get(i));
23491                    }
23492                }
23493            }
23494        }
23495
23496        @Override
23497        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23498            synchronized (mPackages) {
23499                return mPermissionManager.isPermissionsReviewRequired(
23500                        mPackages.get(packageName), userId);
23501            }
23502        }
23503
23504        @Override
23505        public PackageInfo getPackageInfo(
23506                String packageName, int flags, int filterCallingUid, int userId) {
23507            return PackageManagerService.this
23508                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23509                            flags, filterCallingUid, userId);
23510        }
23511
23512        @Override
23513        public int getPackageUid(String packageName, int flags, int userId) {
23514            return PackageManagerService.this
23515                    .getPackageUid(packageName, flags, userId);
23516        }
23517
23518        @Override
23519        public ApplicationInfo getApplicationInfo(
23520                String packageName, int flags, int filterCallingUid, int userId) {
23521            return PackageManagerService.this
23522                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23523        }
23524
23525        @Override
23526        public ActivityInfo getActivityInfo(
23527                ComponentName component, int flags, int filterCallingUid, int userId) {
23528            return PackageManagerService.this
23529                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23530        }
23531
23532        @Override
23533        public List<ResolveInfo> queryIntentActivities(
23534                Intent intent, int flags, int filterCallingUid, int userId) {
23535            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23536            return PackageManagerService.this
23537                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23538                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23539        }
23540
23541        @Override
23542        public List<ResolveInfo> queryIntentServices(
23543                Intent intent, int flags, int callingUid, int userId) {
23544            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23545            return PackageManagerService.this
23546                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23547                            false);
23548        }
23549
23550        @Override
23551        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23552                int userId) {
23553            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23554        }
23555
23556        @Override
23557        public void setDeviceAndProfileOwnerPackages(
23558                int deviceOwnerUserId, String deviceOwnerPackage,
23559                SparseArray<String> profileOwnerPackages) {
23560            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23561                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23562        }
23563
23564        @Override
23565        public boolean isPackageDataProtected(int userId, String packageName) {
23566            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23567        }
23568
23569        @Override
23570        public boolean isPackageEphemeral(int userId, String packageName) {
23571            synchronized (mPackages) {
23572                final PackageSetting ps = mSettings.mPackages.get(packageName);
23573                return ps != null ? ps.getInstantApp(userId) : false;
23574            }
23575        }
23576
23577        @Override
23578        public boolean wasPackageEverLaunched(String packageName, int userId) {
23579            synchronized (mPackages) {
23580                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23581            }
23582        }
23583
23584        @Override
23585        public void grantRuntimePermission(String packageName, String permName, int userId,
23586                boolean overridePolicy) {
23587            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23588                    permName, packageName, overridePolicy, getCallingUid(), userId,
23589                    mPermissionCallback);
23590        }
23591
23592        @Override
23593        public void revokeRuntimePermission(String packageName, String permName, int userId,
23594                boolean overridePolicy) {
23595            mPermissionManager.revokeRuntimePermission(
23596                    permName, packageName, overridePolicy, getCallingUid(), userId,
23597                    mPermissionCallback);
23598        }
23599
23600        @Override
23601        public String getNameForUid(int uid) {
23602            return PackageManagerService.this.getNameForUid(uid);
23603        }
23604
23605        @Override
23606        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23607                Intent origIntent, String resolvedType, String callingPackage,
23608                Bundle verificationBundle, int userId) {
23609            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23610                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23611                    userId);
23612        }
23613
23614        @Override
23615        public void grantEphemeralAccess(int userId, Intent intent,
23616                int targetAppId, int ephemeralAppId) {
23617            synchronized (mPackages) {
23618                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23619                        targetAppId, ephemeralAppId);
23620            }
23621        }
23622
23623        @Override
23624        public boolean isInstantAppInstallerComponent(ComponentName component) {
23625            synchronized (mPackages) {
23626                return mInstantAppInstallerActivity != null
23627                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23628            }
23629        }
23630
23631        @Override
23632        public void pruneInstantApps() {
23633            mInstantAppRegistry.pruneInstantApps();
23634        }
23635
23636        @Override
23637        public String getSetupWizardPackageName() {
23638            return mSetupWizardPackage;
23639        }
23640
23641        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23642            if (policy != null) {
23643                mExternalSourcesPolicy = policy;
23644            }
23645        }
23646
23647        @Override
23648        public boolean isPackagePersistent(String packageName) {
23649            synchronized (mPackages) {
23650                PackageParser.Package pkg = mPackages.get(packageName);
23651                return pkg != null
23652                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23653                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23654                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23655                        : false;
23656            }
23657        }
23658
23659        @Override
23660        public boolean isLegacySystemApp(Package pkg) {
23661            synchronized (mPackages) {
23662                final PackageSetting ps = (PackageSetting) pkg.mExtras;
23663                return mPromoteSystemApps
23664                        && ps.isSystem()
23665                        && mExistingSystemPackages.contains(ps.name);
23666            }
23667        }
23668
23669        @Override
23670        public List<PackageInfo> getOverlayPackages(int userId) {
23671            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23672            synchronized (mPackages) {
23673                for (PackageParser.Package p : mPackages.values()) {
23674                    if (p.mOverlayTarget != null) {
23675                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23676                        if (pkg != null) {
23677                            overlayPackages.add(pkg);
23678                        }
23679                    }
23680                }
23681            }
23682            return overlayPackages;
23683        }
23684
23685        @Override
23686        public List<String> getTargetPackageNames(int userId) {
23687            List<String> targetPackages = new ArrayList<>();
23688            synchronized (mPackages) {
23689                for (PackageParser.Package p : mPackages.values()) {
23690                    if (p.mOverlayTarget == null) {
23691                        targetPackages.add(p.packageName);
23692                    }
23693                }
23694            }
23695            return targetPackages;
23696        }
23697
23698        @Override
23699        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23700                @Nullable List<String> overlayPackageNames) {
23701            synchronized (mPackages) {
23702                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23703                    Slog.e(TAG, "failed to find package " + targetPackageName);
23704                    return false;
23705                }
23706                ArrayList<String> overlayPaths = null;
23707                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
23708                    final int N = overlayPackageNames.size();
23709                    overlayPaths = new ArrayList<>(N);
23710                    for (int i = 0; i < N; i++) {
23711                        final String packageName = overlayPackageNames.get(i);
23712                        final PackageParser.Package pkg = mPackages.get(packageName);
23713                        if (pkg == null) {
23714                            Slog.e(TAG, "failed to find package " + packageName);
23715                            return false;
23716                        }
23717                        overlayPaths.add(pkg.baseCodePath);
23718                    }
23719                }
23720
23721                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
23722                ps.setOverlayPaths(overlayPaths, userId);
23723                return true;
23724            }
23725        }
23726
23727        @Override
23728        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23729                int flags, int userId, boolean resolveForStart) {
23730            return resolveIntentInternal(
23731                    intent, resolvedType, flags, userId, resolveForStart);
23732        }
23733
23734        @Override
23735        public ResolveInfo resolveService(Intent intent, String resolvedType,
23736                int flags, int userId, int callingUid) {
23737            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23738        }
23739
23740        @Override
23741        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
23742            return PackageManagerService.this.resolveContentProviderInternal(
23743                    name, flags, userId);
23744        }
23745
23746        @Override
23747        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23748            synchronized (mPackages) {
23749                mIsolatedOwners.put(isolatedUid, ownerUid);
23750            }
23751        }
23752
23753        @Override
23754        public void removeIsolatedUid(int isolatedUid) {
23755            synchronized (mPackages) {
23756                mIsolatedOwners.delete(isolatedUid);
23757            }
23758        }
23759
23760        @Override
23761        public int getUidTargetSdkVersion(int uid) {
23762            synchronized (mPackages) {
23763                return getUidTargetSdkVersionLockedLPr(uid);
23764            }
23765        }
23766
23767        @Override
23768        public int getPackageTargetSdkVersion(String packageName) {
23769            synchronized (mPackages) {
23770                return getPackageTargetSdkVersionLockedLPr(packageName);
23771            }
23772        }
23773
23774        @Override
23775        public boolean canAccessInstantApps(int callingUid, int userId) {
23776            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
23777        }
23778
23779        @Override
23780        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
23781            synchronized (mPackages) {
23782                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
23783            }
23784        }
23785
23786        @Override
23787        public void notifyPackageUse(String packageName, int reason) {
23788            synchronized (mPackages) {
23789                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
23790            }
23791        }
23792    }
23793
23794    @Override
23795    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23796        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23797        synchronized (mPackages) {
23798            final long identity = Binder.clearCallingIdentity();
23799            try {
23800                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
23801                        packageNames, userId);
23802            } finally {
23803                Binder.restoreCallingIdentity(identity);
23804            }
23805        }
23806    }
23807
23808    @Override
23809    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23810        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23811        synchronized (mPackages) {
23812            final long identity = Binder.clearCallingIdentity();
23813            try {
23814                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
23815                        packageNames, userId);
23816            } finally {
23817                Binder.restoreCallingIdentity(identity);
23818            }
23819        }
23820    }
23821
23822    private static void enforceSystemOrPhoneCaller(String tag) {
23823        int callingUid = Binder.getCallingUid();
23824        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23825            throw new SecurityException(
23826                    "Cannot call " + tag + " from UID " + callingUid);
23827        }
23828    }
23829
23830    boolean isHistoricalPackageUsageAvailable() {
23831        return mPackageUsage.isHistoricalPackageUsageAvailable();
23832    }
23833
23834    /**
23835     * Return a <b>copy</b> of the collection of packages known to the package manager.
23836     * @return A copy of the values of mPackages.
23837     */
23838    Collection<PackageParser.Package> getPackages() {
23839        synchronized (mPackages) {
23840            return new ArrayList<>(mPackages.values());
23841        }
23842    }
23843
23844    /**
23845     * Logs process start information (including base APK hash) to the security log.
23846     * @hide
23847     */
23848    @Override
23849    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23850            String apkFile, int pid) {
23851        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23852            return;
23853        }
23854        if (!SecurityLog.isLoggingEnabled()) {
23855            return;
23856        }
23857        Bundle data = new Bundle();
23858        data.putLong("startTimestamp", System.currentTimeMillis());
23859        data.putString("processName", processName);
23860        data.putInt("uid", uid);
23861        data.putString("seinfo", seinfo);
23862        data.putString("apkFile", apkFile);
23863        data.putInt("pid", pid);
23864        Message msg = mProcessLoggingHandler.obtainMessage(
23865                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23866        msg.setData(data);
23867        mProcessLoggingHandler.sendMessage(msg);
23868    }
23869
23870    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23871        return mCompilerStats.getPackageStats(pkgName);
23872    }
23873
23874    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23875        return getOrCreateCompilerPackageStats(pkg.packageName);
23876    }
23877
23878    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23879        return mCompilerStats.getOrCreatePackageStats(pkgName);
23880    }
23881
23882    public void deleteCompilerPackageStats(String pkgName) {
23883        mCompilerStats.deletePackageStats(pkgName);
23884    }
23885
23886    @Override
23887    public int getInstallReason(String packageName, int userId) {
23888        final int callingUid = Binder.getCallingUid();
23889        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
23890                true /* requireFullPermission */, false /* checkShell */,
23891                "get install reason");
23892        synchronized (mPackages) {
23893            final PackageSetting ps = mSettings.mPackages.get(packageName);
23894            if (filterAppAccessLPr(ps, callingUid, userId)) {
23895                return PackageManager.INSTALL_REASON_UNKNOWN;
23896            }
23897            if (ps != null) {
23898                return ps.getInstallReason(userId);
23899            }
23900        }
23901        return PackageManager.INSTALL_REASON_UNKNOWN;
23902    }
23903
23904    @Override
23905    public boolean canRequestPackageInstalls(String packageName, int userId) {
23906        return canRequestPackageInstallsInternal(packageName, 0, userId,
23907                true /* throwIfPermNotDeclared*/);
23908    }
23909
23910    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
23911            boolean throwIfPermNotDeclared) {
23912        int callingUid = Binder.getCallingUid();
23913        int uid = getPackageUid(packageName, 0, userId);
23914        if (callingUid != uid && callingUid != Process.ROOT_UID
23915                && callingUid != Process.SYSTEM_UID) {
23916            throw new SecurityException(
23917                    "Caller uid " + callingUid + " does not own package " + packageName);
23918        }
23919        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
23920        if (info == null) {
23921            return false;
23922        }
23923        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23924            return false;
23925        }
23926        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23927        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23928        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23929            if (throwIfPermNotDeclared) {
23930                throw new SecurityException("Need to declare " + appOpPermission
23931                        + " to call this api");
23932            } else {
23933                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
23934                return false;
23935            }
23936        }
23937        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23938            return false;
23939        }
23940        if (mExternalSourcesPolicy != null) {
23941            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23942            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23943                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23944            }
23945        }
23946        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23947    }
23948
23949    @Override
23950    public ComponentName getInstantAppResolverSettingsComponent() {
23951        return mInstantAppResolverSettingsComponent;
23952    }
23953
23954    @Override
23955    public ComponentName getInstantAppInstallerComponent() {
23956        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23957            return null;
23958        }
23959        return mInstantAppInstallerActivity == null
23960                ? null : mInstantAppInstallerActivity.getComponentName();
23961    }
23962
23963    @Override
23964    public String getInstantAppAndroidId(String packageName, int userId) {
23965        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
23966                "getInstantAppAndroidId");
23967        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
23968                true /* requireFullPermission */, false /* checkShell */,
23969                "getInstantAppAndroidId");
23970        // Make sure the target is an Instant App.
23971        if (!isInstantApp(packageName, userId)) {
23972            return null;
23973        }
23974        synchronized (mPackages) {
23975            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
23976        }
23977    }
23978
23979    boolean canHaveOatDir(String packageName) {
23980        synchronized (mPackages) {
23981            PackageParser.Package p = mPackages.get(packageName);
23982            if (p == null) {
23983                return false;
23984            }
23985            return p.canHaveOatDir();
23986        }
23987    }
23988
23989    private String getOatDir(PackageParser.Package pkg) {
23990        if (!pkg.canHaveOatDir()) {
23991            return null;
23992        }
23993        File codePath = new File(pkg.codePath);
23994        if (codePath.isDirectory()) {
23995            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
23996        }
23997        return null;
23998    }
23999
24000    void deleteOatArtifactsOfPackage(String packageName) {
24001        final String[] instructionSets;
24002        final List<String> codePaths;
24003        final String oatDir;
24004        final PackageParser.Package pkg;
24005        synchronized (mPackages) {
24006            pkg = mPackages.get(packageName);
24007        }
24008        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24009        codePaths = pkg.getAllCodePaths();
24010        oatDir = getOatDir(pkg);
24011
24012        for (String codePath : codePaths) {
24013            for (String isa : instructionSets) {
24014                try {
24015                    mInstaller.deleteOdex(codePath, isa, oatDir);
24016                } catch (InstallerException e) {
24017                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24018                }
24019            }
24020        }
24021    }
24022
24023    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24024        Set<String> unusedPackages = new HashSet<>();
24025        long currentTimeInMillis = System.currentTimeMillis();
24026        synchronized (mPackages) {
24027            for (PackageParser.Package pkg : mPackages.values()) {
24028                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24029                if (ps == null) {
24030                    continue;
24031                }
24032                PackageDexUsage.PackageUseInfo packageUseInfo =
24033                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24034                if (PackageManagerServiceUtils
24035                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24036                                downgradeTimeThresholdMillis, packageUseInfo,
24037                                pkg.getLatestPackageUseTimeInMills(),
24038                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24039                    unusedPackages.add(pkg.packageName);
24040                }
24041            }
24042        }
24043        return unusedPackages;
24044    }
24045
24046    @Override
24047    public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
24048            int userId) {
24049        final int callingUid = Binder.getCallingUid();
24050        final int callingAppId = UserHandle.getAppId(callingUid);
24051
24052        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24053                true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
24054
24055        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24056                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24057            throw new SecurityException("Caller must have the "
24058                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24059        }
24060
24061        synchronized(mPackages) {
24062            mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
24063            scheduleWritePackageRestrictionsLocked(userId);
24064        }
24065    }
24066
24067    @Nullable
24068    @Override
24069    public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
24070        final int callingUid = Binder.getCallingUid();
24071        final int callingAppId = UserHandle.getAppId(callingUid);
24072
24073        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24074                true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
24075
24076        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24077                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24078            throw new SecurityException("Caller must have the "
24079                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24080        }
24081
24082        synchronized(mPackages) {
24083            return mSettings.getHarmfulAppWarningLPr(packageName, userId);
24084        }
24085    }
24086}
24087
24088interface PackageSender {
24089    /**
24090     * @param userIds User IDs where the action occurred on a full application
24091     * @param instantUserIds User IDs where the action occurred on an instant application
24092     */
24093    void sendPackageBroadcast(final String action, final String pkg,
24094        final Bundle extras, final int flags, final String targetPkg,
24095        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
24096    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24097        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
24098    void notifyPackageAdded(String packageName);
24099    void notifyPackageRemoved(String packageName);
24100}
24101