PackageManagerService.java revision 38d36e5396f259c8c835d6f0a92d9a04858f6076
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.SET_HARMFUL_APP_WARNINGS;
21import static android.Manifest.permission.INSTALL_PACKAGES;
22import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
23import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
24import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
25import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
26import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
27import static android.content.pm.PackageManager.CERT_INPUT_RAW_X509;
28import static android.content.pm.PackageManager.CERT_INPUT_SHA256;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
31import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
32import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
33import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
34import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
39import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
40import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
41import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
42import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
43import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
44import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
45import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
50import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
51import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
52import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
53import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
54import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
55import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
57import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
58import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
66import static android.content.pm.PackageManager.MATCH_ALL;
67import static android.content.pm.PackageManager.MATCH_ANY_USER;
68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.isApkFile;
86import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
87import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
88import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
89import static android.system.OsConstants.O_CREAT;
90import static android.system.OsConstants.O_RDWR;
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
93import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
94import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
95import static com.android.internal.util.ArrayUtils.appendInt;
96import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
99import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
100import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
102import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
103import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures;
104import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists;
105import static com.android.server.pm.PackageManagerServiceUtils.decompressFile;
106import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride;
107import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo;
108import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles;
109import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime;
110import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo;
111import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures;
112import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE;
113import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS;
114import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
115
116import android.Manifest;
117import android.annotation.IntDef;
118import android.annotation.NonNull;
119import android.annotation.Nullable;
120import android.app.ActivityManager;
121import android.app.ActivityManagerInternal;
122import android.app.AppOpsManager;
123import android.app.IActivityManager;
124import android.app.ResourcesManager;
125import android.app.admin.IDevicePolicyManager;
126import android.app.admin.SecurityLog;
127import android.app.backup.IBackupManager;
128import android.content.BroadcastReceiver;
129import android.content.ComponentName;
130import android.content.ContentResolver;
131import android.content.Context;
132import android.content.IIntentReceiver;
133import android.content.Intent;
134import android.content.IntentFilter;
135import android.content.IntentSender;
136import android.content.IntentSender.SendIntentException;
137import android.content.ServiceConnection;
138import android.content.pm.ActivityInfo;
139import android.content.pm.ApplicationInfo;
140import android.content.pm.AppsQueryHelper;
141import android.content.pm.AuxiliaryResolveInfo;
142import android.content.pm.ChangedPackages;
143import android.content.pm.ComponentInfo;
144import android.content.pm.FallbackCategoryProvider;
145import android.content.pm.FeatureInfo;
146import android.content.pm.IDexModuleRegisterCallback;
147import android.content.pm.IOnPermissionsChangeListener;
148import android.content.pm.IPackageDataObserver;
149import android.content.pm.IPackageDeleteObserver;
150import android.content.pm.IPackageDeleteObserver2;
151import android.content.pm.IPackageInstallObserver2;
152import android.content.pm.IPackageInstaller;
153import android.content.pm.IPackageManager;
154import android.content.pm.IPackageManagerNative;
155import android.content.pm.IPackageMoveObserver;
156import android.content.pm.IPackageStatsObserver;
157import android.content.pm.InstantAppInfo;
158import android.content.pm.InstantAppRequest;
159import android.content.pm.InstantAppResolveInfo;
160import android.content.pm.InstrumentationInfo;
161import android.content.pm.IntentFilterVerificationInfo;
162import android.content.pm.KeySet;
163import android.content.pm.PackageCleanItem;
164import android.content.pm.PackageInfo;
165import android.content.pm.PackageInfoLite;
166import android.content.pm.PackageInstaller;
167import android.content.pm.PackageList;
168import android.content.pm.PackageManager;
169import android.content.pm.PackageManagerInternal;
170import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
171import android.content.pm.PackageManagerInternal.PackageListObserver;
172import android.content.pm.PackageParser;
173import android.content.pm.PackageParser.ActivityIntentInfo;
174import android.content.pm.PackageParser.Package;
175import android.content.pm.PackageParser.PackageLite;
176import android.content.pm.PackageParser.PackageParserException;
177import android.content.pm.PackageParser.ParseFlags;
178import android.content.pm.PackageParser.ServiceIntentInfo;
179import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion;
180import android.content.pm.PackageStats;
181import android.content.pm.PackageUserState;
182import android.content.pm.ParceledListSlice;
183import android.content.pm.PermissionGroupInfo;
184import android.content.pm.PermissionInfo;
185import android.content.pm.ProviderInfo;
186import android.content.pm.ResolveInfo;
187import android.content.pm.ServiceInfo;
188import android.content.pm.SharedLibraryInfo;
189import android.content.pm.Signature;
190import android.content.pm.UserInfo;
191import android.content.pm.VerifierDeviceIdentity;
192import android.content.pm.VerifierInfo;
193import android.content.pm.VersionedPackage;
194import android.content.pm.dex.ArtManager;
195import android.content.pm.dex.DexMetadataHelper;
196import android.content.pm.dex.IArtManager;
197import android.content.res.Resources;
198import android.database.ContentObserver;
199import android.graphics.Bitmap;
200import android.hardware.display.DisplayManager;
201import android.net.Uri;
202import android.os.Binder;
203import android.os.Build;
204import android.os.Bundle;
205import android.os.Debug;
206import android.os.Environment;
207import android.os.Environment.UserEnvironment;
208import android.os.FileUtils;
209import android.os.Handler;
210import android.os.IBinder;
211import android.os.Looper;
212import android.os.Message;
213import android.os.Parcel;
214import android.os.ParcelFileDescriptor;
215import android.os.PatternMatcher;
216import android.os.Process;
217import android.os.RemoteCallbackList;
218import android.os.RemoteException;
219import android.os.ResultReceiver;
220import android.os.SELinux;
221import android.os.ServiceManager;
222import android.os.ShellCallback;
223import android.os.SystemClock;
224import android.os.SystemProperties;
225import android.os.Trace;
226import android.os.UserHandle;
227import android.os.UserManager;
228import android.os.UserManagerInternal;
229import android.os.storage.IStorageManager;
230import android.os.storage.StorageEventListener;
231import android.os.storage.StorageManager;
232import android.os.storage.StorageManagerInternal;
233import android.os.storage.VolumeInfo;
234import android.os.storage.VolumeRecord;
235import android.provider.Settings.Global;
236import android.provider.Settings.Secure;
237import android.security.KeyStore;
238import android.security.SystemKeyStore;
239import android.service.pm.PackageServiceDumpProto;
240import android.service.textclassifier.TextClassifierService;
241import android.system.ErrnoException;
242import android.system.Os;
243import android.text.TextUtils;
244import android.text.format.DateUtils;
245import android.util.ArrayMap;
246import android.util.ArraySet;
247import android.util.Base64;
248import android.util.ByteStringUtils;
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_INSTANT = 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    public static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
558
559    public 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        sBrowserIntent.addFlags(Intent.FLAG_IGNORE_EPHEMERAL);
587    }
588
589    /**
590     * The set of all protected actions [i.e. those actions for which a high priority
591     * intent filter is disallowed].
592     */
593    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
594    static {
595        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
596        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
597        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
598        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
599    }
600
601    // Compilation reasons.
602    public static final int REASON_UNKNOWN = -1;
603    public static final int REASON_FIRST_BOOT = 0;
604    public static final int REASON_BOOT = 1;
605    public static final int REASON_INSTALL = 2;
606    public static final int REASON_BACKGROUND_DEXOPT = 3;
607    public static final int REASON_AB_OTA = 4;
608    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
609    public static final int REASON_SHARED = 6;
610
611    public static final int REASON_LAST = REASON_SHARED;
612
613    /**
614     * Version number for the package parser cache. Increment this whenever the format or
615     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
616     */
617    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
618
619    /**
620     * Whether the package parser cache is enabled.
621     */
622    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
623
624    /**
625     * Permissions required in order to receive instant application lifecycle broadcasts.
626     */
627    private static final String[] INSTANT_APP_BROADCAST_PERMISSION =
628            new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS };
629
630    final ServiceThread mHandlerThread;
631
632    final PackageHandler mHandler;
633
634    private final ProcessLoggingHandler mProcessLoggingHandler;
635
636    /**
637     * Messages for {@link #mHandler} that need to wait for system ready before
638     * being dispatched.
639     */
640    private ArrayList<Message> mPostSystemReadyMessages;
641
642    final int mSdkVersion = Build.VERSION.SDK_INT;
643
644    final Context mContext;
645    final boolean mFactoryTest;
646    final boolean mOnlyCore;
647    final DisplayMetrics mMetrics;
648    final int mDefParseFlags;
649    final String[] mSeparateProcesses;
650    final boolean mIsUpgrade;
651    final boolean mIsPreNUpgrade;
652    final boolean mIsPreNMR1Upgrade;
653
654    // Have we told the Activity Manager to whitelist the default container service by uid yet?
655    @GuardedBy("mPackages")
656    boolean mDefaultContainerWhitelisted = false;
657
658    @GuardedBy("mPackages")
659    private boolean mDexOptDialogShown;
660
661    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
662    // LOCK HELD.  Can be called with mInstallLock held.
663    @GuardedBy("mInstallLock")
664    final Installer mInstaller;
665
666    /** Directory where installed applications are stored */
667    private static final File sAppInstallDir =
668            new File(Environment.getDataDirectory(), "app");
669    /** Directory where installed application's 32-bit native libraries are copied. */
670    private static final File sAppLib32InstallDir =
671            new File(Environment.getDataDirectory(), "app-lib");
672    /** Directory where code and non-resource assets of forward-locked applications are stored */
673    private static final File sDrmAppPrivateInstallDir =
674            new File(Environment.getDataDirectory(), "app-private");
675
676    // ----------------------------------------------------------------
677
678    // Lock for state used when installing and doing other long running
679    // operations.  Methods that must be called with this lock held have
680    // the suffix "LI".
681    final Object mInstallLock = new Object();
682
683    // ----------------------------------------------------------------
684
685    // Keys are String (package name), values are Package.  This also serves
686    // as the lock for the global state.  Methods that must be called with
687    // this lock held have the prefix "LP".
688    @GuardedBy("mPackages")
689    final ArrayMap<String, PackageParser.Package> mPackages =
690            new ArrayMap<String, PackageParser.Package>();
691
692    final ArrayMap<String, Set<String>> mKnownCodebase =
693            new ArrayMap<String, Set<String>>();
694
695    // Keys are isolated uids and values are the uid of the application
696    // that created the isolated proccess.
697    @GuardedBy("mPackages")
698    final SparseIntArray mIsolatedOwners = new SparseIntArray();
699
700    /**
701     * Tracks new system packages [received in an OTA] that we expect to
702     * find updated user-installed versions. Keys are package name, values
703     * are package location.
704     */
705    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
706    /**
707     * Tracks high priority intent filters for protected actions. During boot, certain
708     * filter actions are protected and should never be allowed to have a high priority
709     * intent filter for them. However, there is one, and only one exception -- the
710     * setup wizard. It must be able to define a high priority intent filter for these
711     * actions to ensure there are no escapes from the wizard. We need to delay processing
712     * of these during boot as we need to look at all of the system packages in order
713     * to know which component is the setup wizard.
714     */
715    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
716    /**
717     * Whether or not processing protected filters should be deferred.
718     */
719    private boolean mDeferProtectedFilters = true;
720
721    /**
722     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
723     */
724    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
725    /**
726     * Whether or not system app permissions should be promoted from install to runtime.
727     */
728    boolean mPromoteSystemApps;
729
730    @GuardedBy("mPackages")
731    final Settings mSettings;
732
733    /**
734     * Set of package names that are currently "frozen", which means active
735     * surgery is being done on the code/data for that package. The platform
736     * will refuse to launch frozen packages to avoid race conditions.
737     *
738     * @see PackageFreezer
739     */
740    @GuardedBy("mPackages")
741    final ArraySet<String> mFrozenPackages = new ArraySet<>();
742
743    final ProtectedPackages mProtectedPackages;
744
745    @GuardedBy("mLoadedVolumes")
746    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
747
748    boolean mFirstBoot;
749
750    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
751
752    @GuardedBy("mAvailableFeatures")
753    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
754
755    private final InstantAppRegistry mInstantAppRegistry;
756
757    @GuardedBy("mPackages")
758    int mChangedPackagesSequenceNumber;
759    /**
760     * List of changed [installed, removed or updated] packages.
761     * mapping from user id -> sequence number -> package name
762     */
763    @GuardedBy("mPackages")
764    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
765    /**
766     * The sequence number of the last change to a package.
767     * mapping from user id -> package name -> sequence number
768     */
769    @GuardedBy("mPackages")
770    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
771
772    @GuardedBy("mPackages")
773    final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>();
774
775    class PackageParserCallback implements PackageParser.Callback {
776        @Override public final boolean hasFeature(String feature) {
777            return PackageManagerService.this.hasSystemFeature(feature, 0);
778        }
779
780        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
781                Collection<PackageParser.Package> allPackages, String targetPackageName) {
782            List<PackageParser.Package> overlayPackages = null;
783            for (PackageParser.Package p : allPackages) {
784                if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) {
785                    if (overlayPackages == null) {
786                        overlayPackages = new ArrayList<PackageParser.Package>();
787                    }
788                    overlayPackages.add(p);
789                }
790            }
791            if (overlayPackages != null) {
792                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
793                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
794                        return p1.mOverlayPriority - p2.mOverlayPriority;
795                    }
796                };
797                Collections.sort(overlayPackages, cmp);
798            }
799            return overlayPackages;
800        }
801
802        @GuardedBy("mInstallLock")
803        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
804                String targetPackageName, String targetPath) {
805            if ("android".equals(targetPackageName)) {
806                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
807                // native AssetManager.
808                return null;
809            }
810            List<PackageParser.Package> overlayPackages =
811                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
812            if (overlayPackages == null || overlayPackages.isEmpty()) {
813                return null;
814            }
815            List<String> overlayPathList = null;
816            for (PackageParser.Package overlayPackage : overlayPackages) {
817                if (targetPath == null) {
818                    if (overlayPathList == null) {
819                        overlayPathList = new ArrayList<String>();
820                    }
821                    overlayPathList.add(overlayPackage.baseCodePath);
822                    continue;
823                }
824
825                try {
826                    // Creates idmaps for system to parse correctly the Android manifest of the
827                    // target package.
828                    //
829                    // OverlayManagerService will update each of them with a correct gid from its
830                    // target package app id.
831                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
832                            UserHandle.getSharedAppGid(
833                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
834                    if (overlayPathList == null) {
835                        overlayPathList = new ArrayList<String>();
836                    }
837                    overlayPathList.add(overlayPackage.baseCodePath);
838                } catch (InstallerException e) {
839                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
840                            overlayPackage.baseCodePath);
841                }
842            }
843            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
844        }
845
846        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
847            synchronized (mPackages) {
848                return getStaticOverlayPathsLocked(
849                        mPackages.values(), targetPackageName, targetPath);
850            }
851        }
852
853        @Override public final String[] getOverlayApks(String targetPackageName) {
854            return getStaticOverlayPaths(targetPackageName, null);
855        }
856
857        @Override public final String[] getOverlayPaths(String targetPackageName,
858                String targetPath) {
859            return getStaticOverlayPaths(targetPackageName, targetPath);
860        }
861    }
862
863    class ParallelPackageParserCallback extends PackageParserCallback {
864        List<PackageParser.Package> mOverlayPackages = null;
865
866        void findStaticOverlayPackages() {
867            synchronized (mPackages) {
868                for (PackageParser.Package p : mPackages.values()) {
869                    if (p.mOverlayIsStatic) {
870                        if (mOverlayPackages == null) {
871                            mOverlayPackages = new ArrayList<PackageParser.Package>();
872                        }
873                        mOverlayPackages.add(p);
874                    }
875                }
876            }
877        }
878
879        @Override
880        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
881            // We can trust mOverlayPackages without holding mPackages because package uninstall
882            // can't happen while running parallel parsing.
883            // Moreover holding mPackages on each parsing thread causes dead-lock.
884            return mOverlayPackages == null ? null :
885                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
886        }
887    }
888
889    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
890    final ParallelPackageParserCallback mParallelPackageParserCallback =
891            new ParallelPackageParserCallback();
892
893    public static final class SharedLibraryEntry {
894        public final @Nullable String path;
895        public final @Nullable String apk;
896        public final @NonNull SharedLibraryInfo info;
897
898        SharedLibraryEntry(String _path, String _apk, String name, long version, int type,
899                String declaringPackageName, long declaringPackageVersionCode) {
900            path = _path;
901            apk = _apk;
902            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
903                    declaringPackageName, declaringPackageVersionCode), null);
904        }
905    }
906
907    // Currently known shared libraries.
908    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
909    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
910            new ArrayMap<>();
911
912    // All available activities, for your resolving pleasure.
913    final ActivityIntentResolver mActivities =
914            new ActivityIntentResolver();
915
916    // All available receivers, for your resolving pleasure.
917    final ActivityIntentResolver mReceivers =
918            new ActivityIntentResolver();
919
920    // All available services, for your resolving pleasure.
921    final ServiceIntentResolver mServices = new ServiceIntentResolver();
922
923    // All available providers, for your resolving pleasure.
924    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
925
926    // Mapping from provider base names (first directory in content URI codePath)
927    // to the provider information.
928    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
929            new ArrayMap<String, PackageParser.Provider>();
930
931    // Mapping from instrumentation class names to info about them.
932    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
933            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
934
935    // Packages whose data we have transfered into another package, thus
936    // should no longer exist.
937    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
938
939    // Broadcast actions that are only available to the system.
940    @GuardedBy("mProtectedBroadcasts")
941    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
942
943    /** List of packages waiting for verification. */
944    final SparseArray<PackageVerificationState> mPendingVerification
945            = new SparseArray<PackageVerificationState>();
946
947    final PackageInstallerService mInstallerService;
948
949    final ArtManagerService mArtManagerService;
950
951    private final PackageDexOptimizer mPackageDexOptimizer;
952    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
953    // is used by other apps).
954    private final DexManager mDexManager;
955
956    private AtomicInteger mNextMoveId = new AtomicInteger();
957    private final MoveCallbacks mMoveCallbacks;
958
959    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
960
961    // Cache of users who need badging.
962    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
963
964    /** Token for keys in mPendingVerification. */
965    private int mPendingVerificationToken = 0;
966
967    volatile boolean mSystemReady;
968    volatile boolean mSafeMode;
969    volatile boolean mHasSystemUidErrors;
970    private volatile boolean mWebInstantAppsDisabled;
971
972    ApplicationInfo mAndroidApplication;
973    final ActivityInfo mResolveActivity = new ActivityInfo();
974    final ResolveInfo mResolveInfo = new ResolveInfo();
975    ComponentName mResolveComponentName;
976    PackageParser.Package mPlatformPackage;
977    ComponentName mCustomResolverComponentName;
978
979    boolean mResolverReplaced = false;
980
981    private final @Nullable ComponentName mIntentFilterVerifierComponent;
982    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
983
984    private int mIntentFilterVerificationToken = 0;
985
986    /** The service connection to the ephemeral resolver */
987    final InstantAppResolverConnection mInstantAppResolverConnection;
988    /** Component used to show resolver settings for Instant Apps */
989    final ComponentName mInstantAppResolverSettingsComponent;
990
991    /** Activity used to install instant applications */
992    ActivityInfo mInstantAppInstallerActivity;
993    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
994
995    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
996            = new SparseArray<IntentFilterVerificationState>();
997
998    // TODO remove this and go through mPermissonManager directly
999    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1000    private final PermissionManagerInternal mPermissionManager;
1001
1002    // List of packages names to keep cached, even if they are uninstalled for all users
1003    private List<String> mKeepUninstalledPackages;
1004
1005    private UserManagerInternal mUserManagerInternal;
1006    private ActivityManagerInternal mActivityManagerInternal;
1007
1008    private DeviceIdleController.LocalService mDeviceIdleController;
1009
1010    private File mCacheDir;
1011
1012    private Future<?> mPrepareAppDataFuture;
1013
1014    private static class IFVerificationParams {
1015        PackageParser.Package pkg;
1016        boolean replacing;
1017        int userId;
1018        int verifierUid;
1019
1020        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1021                int _userId, int _verifierUid) {
1022            pkg = _pkg;
1023            replacing = _replacing;
1024            userId = _userId;
1025            replacing = _replacing;
1026            verifierUid = _verifierUid;
1027        }
1028    }
1029
1030    private interface IntentFilterVerifier<T extends IntentFilter> {
1031        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1032                                               T filter, String packageName);
1033        void startVerifications(int userId);
1034        void receiveVerificationResponse(int verificationId);
1035    }
1036
1037    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1038        private Context mContext;
1039        private ComponentName mIntentFilterVerifierComponent;
1040        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1041
1042        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1043            mContext = context;
1044            mIntentFilterVerifierComponent = verifierComponent;
1045        }
1046
1047        private String getDefaultScheme() {
1048            return IntentFilter.SCHEME_HTTPS;
1049        }
1050
1051        @Override
1052        public void startVerifications(int userId) {
1053            // Launch verifications requests
1054            int count = mCurrentIntentFilterVerifications.size();
1055            for (int n=0; n<count; n++) {
1056                int verificationId = mCurrentIntentFilterVerifications.get(n);
1057                final IntentFilterVerificationState ivs =
1058                        mIntentFilterVerificationStates.get(verificationId);
1059
1060                String packageName = ivs.getPackageName();
1061
1062                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1063                final int filterCount = filters.size();
1064                ArraySet<String> domainsSet = new ArraySet<>();
1065                for (int m=0; m<filterCount; m++) {
1066                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1067                    domainsSet.addAll(filter.getHostsList());
1068                }
1069                synchronized (mPackages) {
1070                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1071                            packageName, domainsSet) != null) {
1072                        scheduleWriteSettingsLocked();
1073                    }
1074                }
1075                sendVerificationRequest(verificationId, ivs);
1076            }
1077            mCurrentIntentFilterVerifications.clear();
1078        }
1079
1080        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1081            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1082            verificationIntent.putExtra(
1083                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1084                    verificationId);
1085            verificationIntent.putExtra(
1086                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1087                    getDefaultScheme());
1088            verificationIntent.putExtra(
1089                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1090                    ivs.getHostsString());
1091            verificationIntent.putExtra(
1092                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1093                    ivs.getPackageName());
1094            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1095            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1096
1097            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1098            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1099                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1100                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1101
1102            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1103            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1104                    "Sending IntentFilter verification broadcast");
1105        }
1106
1107        public void receiveVerificationResponse(int verificationId) {
1108            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1109
1110            final boolean verified = ivs.isVerified();
1111
1112            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1113            final int count = filters.size();
1114            if (DEBUG_DOMAIN_VERIFICATION) {
1115                Slog.i(TAG, "Received verification response " + verificationId
1116                        + " for " + count + " filters, verified=" + verified);
1117            }
1118            for (int n=0; n<count; n++) {
1119                PackageParser.ActivityIntentInfo filter = filters.get(n);
1120                filter.setVerified(verified);
1121
1122                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1123                        + " verified with result:" + verified + " and hosts:"
1124                        + ivs.getHostsString());
1125            }
1126
1127            mIntentFilterVerificationStates.remove(verificationId);
1128
1129            final String packageName = ivs.getPackageName();
1130            IntentFilterVerificationInfo ivi = null;
1131
1132            synchronized (mPackages) {
1133                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1134            }
1135            if (ivi == null) {
1136                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1137                        + verificationId + " packageName:" + packageName);
1138                return;
1139            }
1140            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1141                    "Updating IntentFilterVerificationInfo for package " + packageName
1142                            +" verificationId:" + verificationId);
1143
1144            synchronized (mPackages) {
1145                if (verified) {
1146                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1147                } else {
1148                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1149                }
1150                scheduleWriteSettingsLocked();
1151
1152                final int userId = ivs.getUserId();
1153                if (userId != UserHandle.USER_ALL) {
1154                    final int userStatus =
1155                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1156
1157                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1158                    boolean needUpdate = false;
1159
1160                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1161                    // already been set by the User thru the Disambiguation dialog
1162                    switch (userStatus) {
1163                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1164                            if (verified) {
1165                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1166                            } else {
1167                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1168                            }
1169                            needUpdate = true;
1170                            break;
1171
1172                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1173                            if (verified) {
1174                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1175                                needUpdate = true;
1176                            }
1177                            break;
1178
1179                        default:
1180                            // Nothing to do
1181                    }
1182
1183                    if (needUpdate) {
1184                        mSettings.updateIntentFilterVerificationStatusLPw(
1185                                packageName, updatedStatus, userId);
1186                        scheduleWritePackageRestrictionsLocked(userId);
1187                    }
1188                }
1189            }
1190        }
1191
1192        @Override
1193        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1194                    ActivityIntentInfo filter, String packageName) {
1195            if (!hasValidDomains(filter)) {
1196                return false;
1197            }
1198            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1199            if (ivs == null) {
1200                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1201                        packageName);
1202            }
1203            if (DEBUG_DOMAIN_VERIFICATION) {
1204                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1205            }
1206            ivs.addFilter(filter);
1207            return true;
1208        }
1209
1210        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1211                int userId, int verificationId, String packageName) {
1212            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1213                    verifierUid, userId, packageName);
1214            ivs.setPendingState();
1215            synchronized (mPackages) {
1216                mIntentFilterVerificationStates.append(verificationId, ivs);
1217                mCurrentIntentFilterVerifications.add(verificationId);
1218            }
1219            return ivs;
1220        }
1221    }
1222
1223    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1224        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1225                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1226                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1227    }
1228
1229    // Set of pending broadcasts for aggregating enable/disable of components.
1230    static class PendingPackageBroadcasts {
1231        // for each user id, a map of <package name -> components within that package>
1232        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1233
1234        public PendingPackageBroadcasts() {
1235            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1236        }
1237
1238        public ArrayList<String> get(int userId, String packageName) {
1239            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1240            return packages.get(packageName);
1241        }
1242
1243        public void put(int userId, String packageName, ArrayList<String> components) {
1244            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1245            packages.put(packageName, components);
1246        }
1247
1248        public void remove(int userId, String packageName) {
1249            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1250            if (packages != null) {
1251                packages.remove(packageName);
1252            }
1253        }
1254
1255        public void remove(int userId) {
1256            mUidMap.remove(userId);
1257        }
1258
1259        public int userIdCount() {
1260            return mUidMap.size();
1261        }
1262
1263        public int userIdAt(int n) {
1264            return mUidMap.keyAt(n);
1265        }
1266
1267        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1268            return mUidMap.get(userId);
1269        }
1270
1271        public int size() {
1272            // total number of pending broadcast entries across all userIds
1273            int num = 0;
1274            for (int i = 0; i< mUidMap.size(); i++) {
1275                num += mUidMap.valueAt(i).size();
1276            }
1277            return num;
1278        }
1279
1280        public void clear() {
1281            mUidMap.clear();
1282        }
1283
1284        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1285            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1286            if (map == null) {
1287                map = new ArrayMap<String, ArrayList<String>>();
1288                mUidMap.put(userId, map);
1289            }
1290            return map;
1291        }
1292    }
1293    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1294
1295    // Service Connection to remote media container service to copy
1296    // package uri's from external media onto secure containers
1297    // or internal storage.
1298    private IMediaContainerService mContainerService = null;
1299
1300    static final int SEND_PENDING_BROADCAST = 1;
1301    static final int MCS_BOUND = 3;
1302    static final int END_COPY = 4;
1303    static final int INIT_COPY = 5;
1304    static final int MCS_UNBIND = 6;
1305    static final int START_CLEANING_PACKAGE = 7;
1306    static final int FIND_INSTALL_LOC = 8;
1307    static final int POST_INSTALL = 9;
1308    static final int MCS_RECONNECT = 10;
1309    static final int MCS_GIVE_UP = 11;
1310    static final int WRITE_SETTINGS = 13;
1311    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1312    static final int PACKAGE_VERIFIED = 15;
1313    static final int CHECK_PENDING_VERIFICATION = 16;
1314    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1315    static final int INTENT_FILTER_VERIFIED = 18;
1316    static final int WRITE_PACKAGE_LIST = 19;
1317    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1318
1319    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1320
1321    // Delay time in millisecs
1322    static final int BROADCAST_DELAY = 10 * 1000;
1323
1324    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1325            2 * 60 * 60 * 1000L; /* two hours */
1326
1327    static UserManagerService sUserManager;
1328
1329    // Stores a list of users whose package restrictions file needs to be updated
1330    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1331
1332    final private DefaultContainerConnection mDefContainerConn =
1333            new DefaultContainerConnection();
1334    class DefaultContainerConnection implements ServiceConnection {
1335        public void onServiceConnected(ComponentName name, IBinder service) {
1336            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1337            final IMediaContainerService imcs = IMediaContainerService.Stub
1338                    .asInterface(Binder.allowBlocking(service));
1339            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1340        }
1341
1342        public void onServiceDisconnected(ComponentName name) {
1343            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1344        }
1345    }
1346
1347    // Recordkeeping of restore-after-install operations that are currently in flight
1348    // between the Package Manager and the Backup Manager
1349    static class PostInstallData {
1350        public InstallArgs args;
1351        public PackageInstalledInfo res;
1352
1353        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1354            args = _a;
1355            res = _r;
1356        }
1357    }
1358
1359    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1360    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1361
1362    // XML tags for backup/restore of various bits of state
1363    private static final String TAG_PREFERRED_BACKUP = "pa";
1364    private static final String TAG_DEFAULT_APPS = "da";
1365    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1366
1367    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1368    private static final String TAG_ALL_GRANTS = "rt-grants";
1369    private static final String TAG_GRANT = "grant";
1370    private static final String ATTR_PACKAGE_NAME = "pkg";
1371
1372    private static final String TAG_PERMISSION = "perm";
1373    private static final String ATTR_PERMISSION_NAME = "name";
1374    private static final String ATTR_IS_GRANTED = "g";
1375    private static final String ATTR_USER_SET = "set";
1376    private static final String ATTR_USER_FIXED = "fixed";
1377    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1378
1379    // System/policy permission grants are not backed up
1380    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1381            FLAG_PERMISSION_POLICY_FIXED
1382            | FLAG_PERMISSION_SYSTEM_FIXED
1383            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1384
1385    // And we back up these user-adjusted states
1386    private static final int USER_RUNTIME_GRANT_MASK =
1387            FLAG_PERMISSION_USER_SET
1388            | FLAG_PERMISSION_USER_FIXED
1389            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1390
1391    final @Nullable String mRequiredVerifierPackage;
1392    final @NonNull String mRequiredInstallerPackage;
1393    final @NonNull String mRequiredUninstallerPackage;
1394    final @Nullable String mSetupWizardPackage;
1395    final @Nullable String mStorageManagerPackage;
1396    final @Nullable String mSystemTextClassifierPackage;
1397    final @NonNull String mServicesSystemSharedLibraryPackageName;
1398    final @NonNull String mSharedSystemSharedLibraryPackageName;
1399
1400    private final PackageUsage mPackageUsage = new PackageUsage();
1401    private final CompilerStats mCompilerStats = new CompilerStats();
1402
1403    class PackageHandler extends Handler {
1404        private boolean mBound = false;
1405        final ArrayList<HandlerParams> mPendingInstalls =
1406            new ArrayList<HandlerParams>();
1407
1408        private boolean connectToService() {
1409            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1410                    " DefaultContainerService");
1411            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1412            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1413            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1414                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1415                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1416                mBound = true;
1417                return true;
1418            }
1419            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1420            return false;
1421        }
1422
1423        private void disconnectService() {
1424            mContainerService = null;
1425            mBound = false;
1426            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1427            mContext.unbindService(mDefContainerConn);
1428            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1429        }
1430
1431        PackageHandler(Looper looper) {
1432            super(looper);
1433        }
1434
1435        public void handleMessage(Message msg) {
1436            try {
1437                doHandleMessage(msg);
1438            } finally {
1439                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1440            }
1441        }
1442
1443        void doHandleMessage(Message msg) {
1444            switch (msg.what) {
1445                case INIT_COPY: {
1446                    HandlerParams params = (HandlerParams) msg.obj;
1447                    int idx = mPendingInstalls.size();
1448                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1449                    // If a bind was already initiated we dont really
1450                    // need to do anything. The pending install
1451                    // will be processed later on.
1452                    if (!mBound) {
1453                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1454                                System.identityHashCode(mHandler));
1455                        // If this is the only one pending we might
1456                        // have to bind to the service again.
1457                        if (!connectToService()) {
1458                            Slog.e(TAG, "Failed to bind to media container service");
1459                            params.serviceError();
1460                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1461                                    System.identityHashCode(mHandler));
1462                            if (params.traceMethod != null) {
1463                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1464                                        params.traceCookie);
1465                            }
1466                            return;
1467                        } else {
1468                            // Once we bind to the service, the first
1469                            // pending request will be processed.
1470                            mPendingInstalls.add(idx, params);
1471                        }
1472                    } else {
1473                        mPendingInstalls.add(idx, params);
1474                        // Already bound to the service. Just make
1475                        // sure we trigger off processing the first request.
1476                        if (idx == 0) {
1477                            mHandler.sendEmptyMessage(MCS_BOUND);
1478                        }
1479                    }
1480                    break;
1481                }
1482                case MCS_BOUND: {
1483                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1484                    if (msg.obj != null) {
1485                        mContainerService = (IMediaContainerService) msg.obj;
1486                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1487                                System.identityHashCode(mHandler));
1488                    }
1489                    if (mContainerService == null) {
1490                        if (!mBound) {
1491                            // Something seriously wrong since we are not bound and we are not
1492                            // waiting for connection. Bail out.
1493                            Slog.e(TAG, "Cannot bind to media container service");
1494                            for (HandlerParams params : mPendingInstalls) {
1495                                // Indicate service bind error
1496                                params.serviceError();
1497                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1498                                        System.identityHashCode(params));
1499                                if (params.traceMethod != null) {
1500                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1501                                            params.traceMethod, params.traceCookie);
1502                                }
1503                                return;
1504                            }
1505                            mPendingInstalls.clear();
1506                        } else {
1507                            Slog.w(TAG, "Waiting to connect to media container service");
1508                        }
1509                    } else if (mPendingInstalls.size() > 0) {
1510                        HandlerParams params = mPendingInstalls.get(0);
1511                        if (params != null) {
1512                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1513                                    System.identityHashCode(params));
1514                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1515                            if (params.startCopy()) {
1516                                // We are done...  look for more work or to
1517                                // go idle.
1518                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1519                                        "Checking for more work or unbind...");
1520                                // Delete pending install
1521                                if (mPendingInstalls.size() > 0) {
1522                                    mPendingInstalls.remove(0);
1523                                }
1524                                if (mPendingInstalls.size() == 0) {
1525                                    if (mBound) {
1526                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1527                                                "Posting delayed MCS_UNBIND");
1528                                        removeMessages(MCS_UNBIND);
1529                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1530                                        // Unbind after a little delay, to avoid
1531                                        // continual thrashing.
1532                                        sendMessageDelayed(ubmsg, 10000);
1533                                    }
1534                                } else {
1535                                    // There are more pending requests in queue.
1536                                    // Just post MCS_BOUND message to trigger processing
1537                                    // of next pending install.
1538                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1539                                            "Posting MCS_BOUND for next work");
1540                                    mHandler.sendEmptyMessage(MCS_BOUND);
1541                                }
1542                            }
1543                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1544                        }
1545                    } else {
1546                        // Should never happen ideally.
1547                        Slog.w(TAG, "Empty queue");
1548                    }
1549                    break;
1550                }
1551                case MCS_RECONNECT: {
1552                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1553                    if (mPendingInstalls.size() > 0) {
1554                        if (mBound) {
1555                            disconnectService();
1556                        }
1557                        if (!connectToService()) {
1558                            Slog.e(TAG, "Failed to bind to media container service");
1559                            for (HandlerParams params : mPendingInstalls) {
1560                                // Indicate service bind error
1561                                params.serviceError();
1562                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1563                                        System.identityHashCode(params));
1564                            }
1565                            mPendingInstalls.clear();
1566                        }
1567                    }
1568                    break;
1569                }
1570                case MCS_UNBIND: {
1571                    // If there is no actual work left, then time to unbind.
1572                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1573
1574                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1575                        if (mBound) {
1576                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1577
1578                            disconnectService();
1579                        }
1580                    } else if (mPendingInstalls.size() > 0) {
1581                        // There are more pending requests in queue.
1582                        // Just post MCS_BOUND message to trigger processing
1583                        // of next pending install.
1584                        mHandler.sendEmptyMessage(MCS_BOUND);
1585                    }
1586
1587                    break;
1588                }
1589                case MCS_GIVE_UP: {
1590                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1591                    HandlerParams params = mPendingInstalls.remove(0);
1592                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1593                            System.identityHashCode(params));
1594                    break;
1595                }
1596                case SEND_PENDING_BROADCAST: {
1597                    String packages[];
1598                    ArrayList<String> components[];
1599                    int size = 0;
1600                    int uids[];
1601                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1602                    synchronized (mPackages) {
1603                        if (mPendingBroadcasts == null) {
1604                            return;
1605                        }
1606                        size = mPendingBroadcasts.size();
1607                        if (size <= 0) {
1608                            // Nothing to be done. Just return
1609                            return;
1610                        }
1611                        packages = new String[size];
1612                        components = new ArrayList[size];
1613                        uids = new int[size];
1614                        int i = 0;  // filling out the above arrays
1615
1616                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1617                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1618                            Iterator<Map.Entry<String, ArrayList<String>>> it
1619                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1620                                            .entrySet().iterator();
1621                            while (it.hasNext() && i < size) {
1622                                Map.Entry<String, ArrayList<String>> ent = it.next();
1623                                packages[i] = ent.getKey();
1624                                components[i] = ent.getValue();
1625                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1626                                uids[i] = (ps != null)
1627                                        ? UserHandle.getUid(packageUserId, ps.appId)
1628                                        : -1;
1629                                i++;
1630                            }
1631                        }
1632                        size = i;
1633                        mPendingBroadcasts.clear();
1634                    }
1635                    // Send broadcasts
1636                    for (int i = 0; i < size; i++) {
1637                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1638                    }
1639                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1640                    break;
1641                }
1642                case START_CLEANING_PACKAGE: {
1643                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1644                    final String packageName = (String)msg.obj;
1645                    final int userId = msg.arg1;
1646                    final boolean andCode = msg.arg2 != 0;
1647                    synchronized (mPackages) {
1648                        if (userId == UserHandle.USER_ALL) {
1649                            int[] users = sUserManager.getUserIds();
1650                            for (int user : users) {
1651                                mSettings.addPackageToCleanLPw(
1652                                        new PackageCleanItem(user, packageName, andCode));
1653                            }
1654                        } else {
1655                            mSettings.addPackageToCleanLPw(
1656                                    new PackageCleanItem(userId, packageName, andCode));
1657                        }
1658                    }
1659                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1660                    startCleaningPackages();
1661                } break;
1662                case POST_INSTALL: {
1663                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1664
1665                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1666                    final boolean didRestore = (msg.arg2 != 0);
1667                    mRunningInstalls.delete(msg.arg1);
1668
1669                    if (data != null) {
1670                        InstallArgs args = data.args;
1671                        PackageInstalledInfo parentRes = data.res;
1672
1673                        final boolean grantPermissions = (args.installFlags
1674                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1675                        final boolean killApp = (args.installFlags
1676                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1677                        final boolean virtualPreload = ((args.installFlags
1678                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1679                        final String[] grantedPermissions = args.installGrantPermissions;
1680
1681                        // Handle the parent package
1682                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1683                                virtualPreload, grantedPermissions, didRestore,
1684                                args.installerPackageName, args.observer);
1685
1686                        // Handle the child packages
1687                        final int childCount = (parentRes.addedChildPackages != null)
1688                                ? parentRes.addedChildPackages.size() : 0;
1689                        for (int i = 0; i < childCount; i++) {
1690                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1691                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1692                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1693                                    args.installerPackageName, args.observer);
1694                        }
1695
1696                        // Log tracing if needed
1697                        if (args.traceMethod != null) {
1698                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1699                                    args.traceCookie);
1700                        }
1701                    } else {
1702                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1703                    }
1704
1705                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1706                } break;
1707                case WRITE_SETTINGS: {
1708                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1709                    synchronized (mPackages) {
1710                        removeMessages(WRITE_SETTINGS);
1711                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1712                        mSettings.writeLPr();
1713                        mDirtyUsers.clear();
1714                    }
1715                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1716                } break;
1717                case WRITE_PACKAGE_RESTRICTIONS: {
1718                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1719                    synchronized (mPackages) {
1720                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1721                        for (int userId : mDirtyUsers) {
1722                            mSettings.writePackageRestrictionsLPr(userId);
1723                        }
1724                        mDirtyUsers.clear();
1725                    }
1726                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1727                } break;
1728                case WRITE_PACKAGE_LIST: {
1729                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1730                    synchronized (mPackages) {
1731                        removeMessages(WRITE_PACKAGE_LIST);
1732                        mSettings.writePackageListLPr(msg.arg1);
1733                    }
1734                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1735                } break;
1736                case CHECK_PENDING_VERIFICATION: {
1737                    final int verificationId = msg.arg1;
1738                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1739
1740                    if ((state != null) && !state.timeoutExtended()) {
1741                        final InstallArgs args = state.getInstallArgs();
1742                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1743
1744                        Slog.i(TAG, "Verification timed out for " + originUri);
1745                        mPendingVerification.remove(verificationId);
1746
1747                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1748
1749                        final UserHandle user = args.getUser();
1750                        if (getDefaultVerificationResponse(user)
1751                                == PackageManager.VERIFICATION_ALLOW) {
1752                            Slog.i(TAG, "Continuing with installation of " + originUri);
1753                            state.setVerifierResponse(Binder.getCallingUid(),
1754                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1755                            broadcastPackageVerified(verificationId, originUri,
1756                                    PackageManager.VERIFICATION_ALLOW, user);
1757                            try {
1758                                ret = args.copyApk(mContainerService, true);
1759                            } catch (RemoteException e) {
1760                                Slog.e(TAG, "Could not contact the ContainerService");
1761                            }
1762                        } else {
1763                            broadcastPackageVerified(verificationId, originUri,
1764                                    PackageManager.VERIFICATION_REJECT, user);
1765                        }
1766
1767                        Trace.asyncTraceEnd(
1768                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1769
1770                        processPendingInstall(args, ret);
1771                        mHandler.sendEmptyMessage(MCS_UNBIND);
1772                    }
1773                    break;
1774                }
1775                case PACKAGE_VERIFIED: {
1776                    final int verificationId = msg.arg1;
1777
1778                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1779                    if (state == null) {
1780                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1781                        break;
1782                    }
1783
1784                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1785
1786                    state.setVerifierResponse(response.callerUid, response.code);
1787
1788                    if (state.isVerificationComplete()) {
1789                        mPendingVerification.remove(verificationId);
1790
1791                        final InstallArgs args = state.getInstallArgs();
1792                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1793
1794                        int ret;
1795                        if (state.isInstallAllowed()) {
1796                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1797                            broadcastPackageVerified(verificationId, originUri,
1798                                    response.code, state.getInstallArgs().getUser());
1799                            try {
1800                                ret = args.copyApk(mContainerService, true);
1801                            } catch (RemoteException e) {
1802                                Slog.e(TAG, "Could not contact the ContainerService");
1803                            }
1804                        } else {
1805                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1806                        }
1807
1808                        Trace.asyncTraceEnd(
1809                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1810
1811                        processPendingInstall(args, ret);
1812                        mHandler.sendEmptyMessage(MCS_UNBIND);
1813                    }
1814
1815                    break;
1816                }
1817                case START_INTENT_FILTER_VERIFICATIONS: {
1818                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1819                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1820                            params.replacing, params.pkg);
1821                    break;
1822                }
1823                case INTENT_FILTER_VERIFIED: {
1824                    final int verificationId = msg.arg1;
1825
1826                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1827                            verificationId);
1828                    if (state == null) {
1829                        Slog.w(TAG, "Invalid IntentFilter verification token "
1830                                + verificationId + " received");
1831                        break;
1832                    }
1833
1834                    final int userId = state.getUserId();
1835
1836                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1837                            "Processing IntentFilter verification with token:"
1838                            + verificationId + " and userId:" + userId);
1839
1840                    final IntentFilterVerificationResponse response =
1841                            (IntentFilterVerificationResponse) msg.obj;
1842
1843                    state.setVerifierResponse(response.callerUid, response.code);
1844
1845                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1846                            "IntentFilter verification with token:" + verificationId
1847                            + " and userId:" + userId
1848                            + " is settings verifier response with response code:"
1849                            + response.code);
1850
1851                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1852                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1853                                + response.getFailedDomainsString());
1854                    }
1855
1856                    if (state.isVerificationComplete()) {
1857                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1858                    } else {
1859                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1860                                "IntentFilter verification with token:" + verificationId
1861                                + " was not said to be complete");
1862                    }
1863
1864                    break;
1865                }
1866                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1867                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1868                            mInstantAppResolverConnection,
1869                            (InstantAppRequest) msg.obj,
1870                            mInstantAppInstallerActivity,
1871                            mHandler);
1872                }
1873            }
1874        }
1875    }
1876
1877    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1878        @Override
1879        public void onGidsChanged(int appId, int userId) {
1880            mHandler.post(new Runnable() {
1881                @Override
1882                public void run() {
1883                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1884                }
1885            });
1886        }
1887        @Override
1888        public void onPermissionGranted(int uid, int userId) {
1889            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1890
1891            // Not critical; if this is lost, the application has to request again.
1892            synchronized (mPackages) {
1893                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1894            }
1895        }
1896        @Override
1897        public void onInstallPermissionGranted() {
1898            synchronized (mPackages) {
1899                scheduleWriteSettingsLocked();
1900            }
1901        }
1902        @Override
1903        public void onPermissionRevoked(int uid, int userId) {
1904            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1905
1906            synchronized (mPackages) {
1907                // Critical; after this call the application should never have the permission
1908                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1909            }
1910
1911            final int appId = UserHandle.getAppId(uid);
1912            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1913        }
1914        @Override
1915        public void onInstallPermissionRevoked() {
1916            synchronized (mPackages) {
1917                scheduleWriteSettingsLocked();
1918            }
1919        }
1920        @Override
1921        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1922            synchronized (mPackages) {
1923                for (int userId : updatedUserIds) {
1924                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1925                }
1926            }
1927        }
1928        @Override
1929        public void onInstallPermissionUpdated() {
1930            synchronized (mPackages) {
1931                scheduleWriteSettingsLocked();
1932            }
1933        }
1934        @Override
1935        public void onPermissionRemoved() {
1936            synchronized (mPackages) {
1937                mSettings.writeLPr();
1938            }
1939        }
1940    };
1941
1942    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1943            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1944            boolean launchedForRestore, String installerPackage,
1945            IPackageInstallObserver2 installObserver) {
1946        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1947            // Send the removed broadcasts
1948            if (res.removedInfo != null) {
1949                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1950            }
1951
1952            // Now that we successfully installed the package, grant runtime
1953            // permissions if requested before broadcasting the install. Also
1954            // for legacy apps in permission review mode we clear the permission
1955            // review flag which is used to emulate runtime permissions for
1956            // legacy apps.
1957            if (grantPermissions) {
1958                final int callingUid = Binder.getCallingUid();
1959                mPermissionManager.grantRequestedRuntimePermissions(
1960                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1961                        mPermissionCallback);
1962            }
1963
1964            final boolean update = res.removedInfo != null
1965                    && res.removedInfo.removedPackage != null;
1966            final String installerPackageName =
1967                    res.installerPackageName != null
1968                            ? res.installerPackageName
1969                            : res.removedInfo != null
1970                                    ? res.removedInfo.installerPackageName
1971                                    : null;
1972
1973            // If this is the first time we have child packages for a disabled privileged
1974            // app that had no children, we grant requested runtime permissions to the new
1975            // children if the parent on the system image had them already granted.
1976            if (res.pkg.parentPackage != null) {
1977                final int callingUid = Binder.getCallingUid();
1978                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1979                        res.pkg, callingUid, mPermissionCallback);
1980            }
1981
1982            synchronized (mPackages) {
1983                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1984            }
1985
1986            final String packageName = res.pkg.applicationInfo.packageName;
1987
1988            // Determine the set of users who are adding this package for
1989            // the first time vs. those who are seeing an update.
1990            int[] firstUserIds = EMPTY_INT_ARRAY;
1991            int[] firstInstantUserIds = EMPTY_INT_ARRAY;
1992            int[] updateUserIds = EMPTY_INT_ARRAY;
1993            int[] instantUserIds = EMPTY_INT_ARRAY;
1994            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1995            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1996            for (int newUser : res.newUsers) {
1997                final boolean isInstantApp = ps.getInstantApp(newUser);
1998                if (allNewUsers) {
1999                    if (isInstantApp) {
2000                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2001                    } else {
2002                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2003                    }
2004                    continue;
2005                }
2006                boolean isNew = true;
2007                for (int origUser : res.origUsers) {
2008                    if (origUser == newUser) {
2009                        isNew = false;
2010                        break;
2011                    }
2012                }
2013                if (isNew) {
2014                    if (isInstantApp) {
2015                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2016                    } else {
2017                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2018                    }
2019                } else {
2020                    if (isInstantApp) {
2021                        instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser);
2022                    } else {
2023                        updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser);
2024                    }
2025                }
2026            }
2027
2028            // Send installed broadcasts if the package is not a static shared lib.
2029            if (res.pkg.staticSharedLibName == null) {
2030                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2031
2032                // Send added for users that see the package for the first time
2033                // sendPackageAddedForNewUsers also deals with system apps
2034                int appId = UserHandle.getAppId(res.uid);
2035                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2036                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2037                        virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds);
2038
2039                // Send added for users that don't see the package for the first time
2040                Bundle extras = new Bundle(1);
2041                extras.putInt(Intent.EXTRA_UID, res.uid);
2042                if (update) {
2043                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2044                }
2045                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2046                        extras, 0 /*flags*/,
2047                        null /*targetPackage*/, null /*finishedReceiver*/,
2048                        updateUserIds, instantUserIds);
2049                if (installerPackageName != null) {
2050                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2051                            extras, 0 /*flags*/,
2052                            installerPackageName, null /*finishedReceiver*/,
2053                            updateUserIds, instantUserIds);
2054                }
2055
2056                // Send replaced for users that don't see the package for the first time
2057                if (update) {
2058                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2059                            packageName, extras, 0 /*flags*/,
2060                            null /*targetPackage*/, null /*finishedReceiver*/,
2061                            updateUserIds, instantUserIds);
2062                    if (installerPackageName != null) {
2063                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2064                                extras, 0 /*flags*/,
2065                                installerPackageName, null /*finishedReceiver*/,
2066                                updateUserIds, instantUserIds);
2067                    }
2068                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2069                            null /*package*/, null /*extras*/, 0 /*flags*/,
2070                            packageName /*targetPackage*/,
2071                            null /*finishedReceiver*/, updateUserIds, instantUserIds);
2072                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2073                    // First-install and we did a restore, so we're responsible for the
2074                    // first-launch broadcast.
2075                    if (DEBUG_BACKUP) {
2076                        Slog.i(TAG, "Post-restore of " + packageName
2077                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds));
2078                    }
2079                    sendFirstLaunchBroadcast(packageName, installerPackage,
2080                            firstUserIds, firstInstantUserIds);
2081                }
2082
2083                // Send broadcast package appeared if forward locked/external for all users
2084                // treat asec-hosted packages like removable media on upgrade
2085                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2086                    if (DEBUG_INSTALL) {
2087                        Slog.i(TAG, "upgrading pkg " + res.pkg
2088                                + " is ASEC-hosted -> AVAILABLE");
2089                    }
2090                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2091                    ArrayList<String> pkgList = new ArrayList<>(1);
2092                    pkgList.add(packageName);
2093                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2094                }
2095            }
2096
2097            // Work that needs to happen on first install within each user
2098            if (firstUserIds != null && firstUserIds.length > 0) {
2099                synchronized (mPackages) {
2100                    for (int userId : firstUserIds) {
2101                        // If this app is a browser and it's newly-installed for some
2102                        // users, clear any default-browser state in those users. The
2103                        // app's nature doesn't depend on the user, so we can just check
2104                        // its browser nature in any user and generalize.
2105                        if (packageIsBrowser(packageName, userId)) {
2106                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2107                        }
2108
2109                        // We may also need to apply pending (restored) runtime
2110                        // permission grants within these users.
2111                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2112                    }
2113                }
2114            }
2115
2116            if (allNewUsers && !update) {
2117                notifyPackageAdded(packageName);
2118            }
2119
2120            // Log current value of "unknown sources" setting
2121            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2122                    getUnknownSourcesSettings());
2123
2124            // Remove the replaced package's older resources safely now
2125            // We delete after a gc for applications  on sdcard.
2126            if (res.removedInfo != null && res.removedInfo.args != null) {
2127                Runtime.getRuntime().gc();
2128                synchronized (mInstallLock) {
2129                    res.removedInfo.args.doPostDeleteLI(true);
2130                }
2131            } else {
2132                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2133                // and not block here.
2134                VMRuntime.getRuntime().requestConcurrentGC();
2135            }
2136
2137            // Notify DexManager that the package was installed for new users.
2138            // The updated users should already be indexed and the package code paths
2139            // should not change.
2140            // Don't notify the manager for ephemeral apps as they are not expected to
2141            // survive long enough to benefit of background optimizations.
2142            for (int userId : firstUserIds) {
2143                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2144                // There's a race currently where some install events may interleave with an uninstall.
2145                // This can lead to package info being null (b/36642664).
2146                if (info != null) {
2147                    mDexManager.notifyPackageInstalled(info, userId);
2148                }
2149            }
2150        }
2151
2152        // If someone is watching installs - notify them
2153        if (installObserver != null) {
2154            try {
2155                Bundle extras = extrasForInstallResult(res);
2156                installObserver.onPackageInstalled(res.name, res.returnCode,
2157                        res.returnMsg, extras);
2158            } catch (RemoteException e) {
2159                Slog.i(TAG, "Observer no longer exists.");
2160            }
2161        }
2162    }
2163
2164    private StorageEventListener mStorageListener = new StorageEventListener() {
2165        @Override
2166        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2167            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2168                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2169                    final String volumeUuid = vol.getFsUuid();
2170
2171                    // Clean up any users or apps that were removed or recreated
2172                    // while this volume was missing
2173                    sUserManager.reconcileUsers(volumeUuid);
2174                    reconcileApps(volumeUuid);
2175
2176                    // Clean up any install sessions that expired or were
2177                    // cancelled while this volume was missing
2178                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2179
2180                    loadPrivatePackages(vol);
2181
2182                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2183                    unloadPrivatePackages(vol);
2184                }
2185            }
2186        }
2187
2188        @Override
2189        public void onVolumeForgotten(String fsUuid) {
2190            if (TextUtils.isEmpty(fsUuid)) {
2191                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2192                return;
2193            }
2194
2195            // Remove any apps installed on the forgotten volume
2196            synchronized (mPackages) {
2197                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2198                for (PackageSetting ps : packages) {
2199                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2200                    deletePackageVersioned(new VersionedPackage(ps.name,
2201                            PackageManager.VERSION_CODE_HIGHEST),
2202                            new LegacyPackageDeleteObserver(null).getBinder(),
2203                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2204                    // Try very hard to release any references to this package
2205                    // so we don't risk the system server being killed due to
2206                    // open FDs
2207                    AttributeCache.instance().removePackage(ps.name);
2208                }
2209
2210                mSettings.onVolumeForgotten(fsUuid);
2211                mSettings.writeLPr();
2212            }
2213        }
2214    };
2215
2216    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2217        Bundle extras = null;
2218        switch (res.returnCode) {
2219            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2220                extras = new Bundle();
2221                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2222                        res.origPermission);
2223                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2224                        res.origPackage);
2225                break;
2226            }
2227            case PackageManager.INSTALL_SUCCEEDED: {
2228                extras = new Bundle();
2229                extras.putBoolean(Intent.EXTRA_REPLACING,
2230                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2231                break;
2232            }
2233        }
2234        return extras;
2235    }
2236
2237    void scheduleWriteSettingsLocked() {
2238        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2239            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2240        }
2241    }
2242
2243    void scheduleWritePackageListLocked(int userId) {
2244        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2245            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2246            msg.arg1 = userId;
2247            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2248        }
2249    }
2250
2251    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2252        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2253        scheduleWritePackageRestrictionsLocked(userId);
2254    }
2255
2256    void scheduleWritePackageRestrictionsLocked(int userId) {
2257        final int[] userIds = (userId == UserHandle.USER_ALL)
2258                ? sUserManager.getUserIds() : new int[]{userId};
2259        for (int nextUserId : userIds) {
2260            if (!sUserManager.exists(nextUserId)) return;
2261            mDirtyUsers.add(nextUserId);
2262            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2263                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2264            }
2265        }
2266    }
2267
2268    public static PackageManagerService main(Context context, Installer installer,
2269            boolean factoryTest, boolean onlyCore) {
2270        // Self-check for initial settings.
2271        PackageManagerServiceCompilerMapping.checkProperties();
2272
2273        PackageManagerService m = new PackageManagerService(context, installer,
2274                factoryTest, onlyCore);
2275        m.enableSystemUserPackages();
2276        ServiceManager.addService("package", m);
2277        final PackageManagerNative pmn = m.new PackageManagerNative();
2278        ServiceManager.addService("package_native", pmn);
2279        return m;
2280    }
2281
2282    private void enableSystemUserPackages() {
2283        if (!UserManager.isSplitSystemUser()) {
2284            return;
2285        }
2286        // For system user, enable apps based on the following conditions:
2287        // - app is whitelisted or belong to one of these groups:
2288        //   -- system app which has no launcher icons
2289        //   -- system app which has INTERACT_ACROSS_USERS permission
2290        //   -- system IME app
2291        // - app is not in the blacklist
2292        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2293        Set<String> enableApps = new ArraySet<>();
2294        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2295                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2296                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2297        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2298        enableApps.addAll(wlApps);
2299        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2300                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2301        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2302        enableApps.removeAll(blApps);
2303        Log.i(TAG, "Applications installed for system user: " + enableApps);
2304        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2305                UserHandle.SYSTEM);
2306        final int allAppsSize = allAps.size();
2307        synchronized (mPackages) {
2308            for (int i = 0; i < allAppsSize; i++) {
2309                String pName = allAps.get(i);
2310                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2311                // Should not happen, but we shouldn't be failing if it does
2312                if (pkgSetting == null) {
2313                    continue;
2314                }
2315                boolean install = enableApps.contains(pName);
2316                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2317                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2318                            + " for system user");
2319                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2320                }
2321            }
2322            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2323        }
2324    }
2325
2326    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2327        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2328                Context.DISPLAY_SERVICE);
2329        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2330    }
2331
2332    /**
2333     * Requests that files preopted on a secondary system partition be copied to the data partition
2334     * if possible.  Note that the actual copying of the files is accomplished by init for security
2335     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2336     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2337     */
2338    private static void requestCopyPreoptedFiles() {
2339        final int WAIT_TIME_MS = 100;
2340        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2341        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2342            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2343            // We will wait for up to 100 seconds.
2344            final long timeStart = SystemClock.uptimeMillis();
2345            final long timeEnd = timeStart + 100 * 1000;
2346            long timeNow = timeStart;
2347            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2348                try {
2349                    Thread.sleep(WAIT_TIME_MS);
2350                } catch (InterruptedException e) {
2351                    // Do nothing
2352                }
2353                timeNow = SystemClock.uptimeMillis();
2354                if (timeNow > timeEnd) {
2355                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2356                    Slog.wtf(TAG, "cppreopt did not finish!");
2357                    break;
2358                }
2359            }
2360
2361            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2362        }
2363    }
2364
2365    public PackageManagerService(Context context, Installer installer,
2366            boolean factoryTest, boolean onlyCore) {
2367        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2368        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2369        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2370                SystemClock.uptimeMillis());
2371
2372        if (mSdkVersion <= 0) {
2373            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2374        }
2375
2376        mContext = context;
2377
2378        mFactoryTest = factoryTest;
2379        mOnlyCore = onlyCore;
2380        mMetrics = new DisplayMetrics();
2381        mInstaller = installer;
2382
2383        // Create sub-components that provide services / data. Order here is important.
2384        synchronized (mInstallLock) {
2385        synchronized (mPackages) {
2386            // Expose private service for system components to use.
2387            LocalServices.addService(
2388                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2389            sUserManager = new UserManagerService(context, this,
2390                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2391            mPermissionManager = PermissionManagerService.create(context,
2392                    new DefaultPermissionGrantedCallback() {
2393                        @Override
2394                        public void onDefaultRuntimePermissionsGranted(int userId) {
2395                            synchronized(mPackages) {
2396                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2397                            }
2398                        }
2399                    }, mPackages /*externalLock*/);
2400            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2401            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2402        }
2403        }
2404        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2405                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2406        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2407                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2408        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2409                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2410        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2411                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2412        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2413                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2414        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2415                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2416        mSettings.addSharedUserLPw("android.uid.se", SE_UID,
2417                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2418
2419        String separateProcesses = SystemProperties.get("debug.separate_processes");
2420        if (separateProcesses != null && separateProcesses.length() > 0) {
2421            if ("*".equals(separateProcesses)) {
2422                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2423                mSeparateProcesses = null;
2424                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2425            } else {
2426                mDefParseFlags = 0;
2427                mSeparateProcesses = separateProcesses.split(",");
2428                Slog.w(TAG, "Running with debug.separate_processes: "
2429                        + separateProcesses);
2430            }
2431        } else {
2432            mDefParseFlags = 0;
2433            mSeparateProcesses = null;
2434        }
2435
2436        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2437                "*dexopt*");
2438        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2439                installer, mInstallLock);
2440        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2441                dexManagerListener);
2442        mArtManagerService = new ArtManagerService(this, installer, mInstallLock);
2443        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2444
2445        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2446                FgThread.get().getLooper());
2447
2448        getDefaultDisplayMetrics(context, mMetrics);
2449
2450        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2451        SystemConfig systemConfig = SystemConfig.getInstance();
2452        mAvailableFeatures = systemConfig.getAvailableFeatures();
2453        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2454
2455        mProtectedPackages = new ProtectedPackages(mContext);
2456
2457        synchronized (mInstallLock) {
2458        // writer
2459        synchronized (mPackages) {
2460            mHandlerThread = new ServiceThread(TAG,
2461                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2462            mHandlerThread.start();
2463            mHandler = new PackageHandler(mHandlerThread.getLooper());
2464            mProcessLoggingHandler = new ProcessLoggingHandler();
2465            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2466            mInstantAppRegistry = new InstantAppRegistry(this);
2467
2468            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2469            final int builtInLibCount = libConfig.size();
2470            for (int i = 0; i < builtInLibCount; i++) {
2471                String name = libConfig.keyAt(i);
2472                String path = libConfig.valueAt(i);
2473                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2474                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2475            }
2476
2477            SELinuxMMAC.readInstallPolicy();
2478
2479            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2480            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2481            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2482
2483            // Clean up orphaned packages for which the code path doesn't exist
2484            // and they are an update to a system app - caused by bug/32321269
2485            final int packageSettingCount = mSettings.mPackages.size();
2486            for (int i = packageSettingCount - 1; i >= 0; i--) {
2487                PackageSetting ps = mSettings.mPackages.valueAt(i);
2488                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2489                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2490                    mSettings.mPackages.removeAt(i);
2491                    mSettings.enableSystemPackageLPw(ps.name);
2492                }
2493            }
2494
2495            if (mFirstBoot) {
2496                requestCopyPreoptedFiles();
2497            }
2498
2499            String customResolverActivity = Resources.getSystem().getString(
2500                    R.string.config_customResolverActivity);
2501            if (TextUtils.isEmpty(customResolverActivity)) {
2502                customResolverActivity = null;
2503            } else {
2504                mCustomResolverComponentName = ComponentName.unflattenFromString(
2505                        customResolverActivity);
2506            }
2507
2508            long startTime = SystemClock.uptimeMillis();
2509
2510            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2511                    startTime);
2512
2513            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2514            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2515
2516            if (bootClassPath == null) {
2517                Slog.w(TAG, "No BOOTCLASSPATH found!");
2518            }
2519
2520            if (systemServerClassPath == null) {
2521                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2522            }
2523
2524            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2525
2526            final VersionInfo ver = mSettings.getInternalVersion();
2527            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2528            if (mIsUpgrade) {
2529                logCriticalInfo(Log.INFO,
2530                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2531            }
2532
2533            // when upgrading from pre-M, promote system app permissions from install to runtime
2534            mPromoteSystemApps =
2535                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2536
2537            // When upgrading from pre-N, we need to handle package extraction like first boot,
2538            // as there is no profiling data available.
2539            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2540
2541            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2542
2543            // save off the names of pre-existing system packages prior to scanning; we don't
2544            // want to automatically grant runtime permissions for new system apps
2545            if (mPromoteSystemApps) {
2546                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2547                while (pkgSettingIter.hasNext()) {
2548                    PackageSetting ps = pkgSettingIter.next();
2549                    if (isSystemApp(ps)) {
2550                        mExistingSystemPackages.add(ps.name);
2551                    }
2552                }
2553            }
2554
2555            mCacheDir = preparePackageParserCache(mIsUpgrade);
2556
2557            // Set flag to monitor and not change apk file paths when
2558            // scanning install directories.
2559            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2560
2561            if (mIsUpgrade || mFirstBoot) {
2562                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2563            }
2564
2565            // Collect vendor/product overlay packages. (Do this before scanning any apps.)
2566            // For security and version matching reason, only consider
2567            // overlay packages if they reside in the right directory.
2568            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2569                    mDefParseFlags
2570                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2571                    scanFlags
2572                    | SCAN_AS_SYSTEM
2573                    | SCAN_AS_VENDOR,
2574                    0);
2575            scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR),
2576                    mDefParseFlags
2577                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2578                    scanFlags
2579                    | SCAN_AS_SYSTEM
2580                    | SCAN_AS_PRODUCT,
2581                    0);
2582
2583            mParallelPackageParserCallback.findStaticOverlayPackages();
2584
2585            // Find base frameworks (resource packages without code).
2586            scanDirTracedLI(frameworkDir,
2587                    mDefParseFlags
2588                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2589                    scanFlags
2590                    | SCAN_NO_DEX
2591                    | SCAN_AS_SYSTEM
2592                    | SCAN_AS_PRIVILEGED,
2593                    0);
2594
2595            // Collected privileged system packages.
2596            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2597            scanDirTracedLI(privilegedAppDir,
2598                    mDefParseFlags
2599                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2600                    scanFlags
2601                    | SCAN_AS_SYSTEM
2602                    | SCAN_AS_PRIVILEGED,
2603                    0);
2604
2605            // Collect ordinary system packages.
2606            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2607            scanDirTracedLI(systemAppDir,
2608                    mDefParseFlags
2609                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2610                    scanFlags
2611                    | SCAN_AS_SYSTEM,
2612                    0);
2613
2614            // Collected privileged vendor packages.
2615            File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
2616            try {
2617                privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
2618            } catch (IOException e) {
2619                // failed to look up canonical path, continue with original one
2620            }
2621            scanDirTracedLI(privilegedVendorAppDir,
2622                    mDefParseFlags
2623                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2624                    scanFlags
2625                    | SCAN_AS_SYSTEM
2626                    | SCAN_AS_VENDOR
2627                    | SCAN_AS_PRIVILEGED,
2628                    0);
2629
2630            // Collect ordinary vendor packages.
2631            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2632            try {
2633                vendorAppDir = vendorAppDir.getCanonicalFile();
2634            } catch (IOException e) {
2635                // failed to look up canonical path, continue with original one
2636            }
2637            scanDirTracedLI(vendorAppDir,
2638                    mDefParseFlags
2639                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2640                    scanFlags
2641                    | SCAN_AS_SYSTEM
2642                    | SCAN_AS_VENDOR,
2643                    0);
2644
2645            // Collect all OEM packages.
2646            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2647            scanDirTracedLI(oemAppDir,
2648                    mDefParseFlags
2649                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2650                    scanFlags
2651                    | SCAN_AS_SYSTEM
2652                    | SCAN_AS_OEM,
2653                    0);
2654
2655            // Collected privileged product packages.
2656            File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
2657            try {
2658                privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile();
2659            } catch (IOException e) {
2660                // failed to look up canonical path, continue with original one
2661            }
2662            scanDirTracedLI(privilegedProductAppDir,
2663                    mDefParseFlags
2664                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2665                    scanFlags
2666                    | SCAN_AS_SYSTEM
2667                    | SCAN_AS_PRODUCT
2668                    | SCAN_AS_PRIVILEGED,
2669                    0);
2670
2671            // Collect ordinary product packages.
2672            File productAppDir = new File(Environment.getProductDirectory(), "app");
2673            try {
2674                productAppDir = productAppDir.getCanonicalFile();
2675            } catch (IOException e) {
2676                // failed to look up canonical path, continue with original one
2677            }
2678            scanDirTracedLI(productAppDir,
2679                    mDefParseFlags
2680                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2681                    scanFlags
2682                    | SCAN_AS_SYSTEM
2683                    | SCAN_AS_PRODUCT,
2684                    0);
2685
2686            // Prune any system packages that no longer exist.
2687            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2688            // Stub packages must either be replaced with full versions in the /data
2689            // partition or be disabled.
2690            final List<String> stubSystemApps = new ArrayList<>();
2691            if (!mOnlyCore) {
2692                // do this first before mucking with mPackages for the "expecting better" case
2693                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2694                while (pkgIterator.hasNext()) {
2695                    final PackageParser.Package pkg = pkgIterator.next();
2696                    if (pkg.isStub) {
2697                        stubSystemApps.add(pkg.packageName);
2698                    }
2699                }
2700
2701                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2702                while (psit.hasNext()) {
2703                    PackageSetting ps = psit.next();
2704
2705                    /*
2706                     * If this is not a system app, it can't be a
2707                     * disable system app.
2708                     */
2709                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2710                        continue;
2711                    }
2712
2713                    /*
2714                     * If the package is scanned, it's not erased.
2715                     */
2716                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2717                    if (scannedPkg != null) {
2718                        /*
2719                         * If the system app is both scanned and in the
2720                         * disabled packages list, then it must have been
2721                         * added via OTA. Remove it from the currently
2722                         * scanned package so the previously user-installed
2723                         * application can be scanned.
2724                         */
2725                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2726                            logCriticalInfo(Log.WARN,
2727                                    "Expecting better updated system app for " + ps.name
2728                                    + "; removing system app.  Last known"
2729                                    + " codePath=" + ps.codePathString
2730                                    + ", versionCode=" + ps.versionCode
2731                                    + "; scanned versionCode=" + scannedPkg.getLongVersionCode());
2732                            removePackageLI(scannedPkg, true);
2733                            mExpectingBetter.put(ps.name, ps.codePath);
2734                        }
2735
2736                        continue;
2737                    }
2738
2739                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2740                        psit.remove();
2741                        logCriticalInfo(Log.WARN, "System package " + ps.name
2742                                + " no longer exists; it's data will be wiped");
2743                        // Actual deletion of code and data will be handled by later
2744                        // reconciliation step
2745                    } else {
2746                        // we still have a disabled system package, but, it still might have
2747                        // been removed. check the code path still exists and check there's
2748                        // still a package. the latter can happen if an OTA keeps the same
2749                        // code path, but, changes the package name.
2750                        final PackageSetting disabledPs =
2751                                mSettings.getDisabledSystemPkgLPr(ps.name);
2752                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2753                                || disabledPs.pkg == null) {
2754                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2755                        }
2756                    }
2757                }
2758            }
2759
2760            //delete tmp files
2761            deleteTempPackageFiles();
2762
2763            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2764
2765            // Remove any shared userIDs that have no associated packages
2766            mSettings.pruneSharedUsersLPw();
2767            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2768            final int systemPackagesCount = mPackages.size();
2769            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2770                    + " ms, packageCount: " + systemPackagesCount
2771                    + " , timePerPackage: "
2772                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2773                    + " , cached: " + cachedSystemApps);
2774            if (mIsUpgrade && systemPackagesCount > 0) {
2775                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2776                        ((int) systemScanTime) / systemPackagesCount);
2777            }
2778            if (!mOnlyCore) {
2779                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2780                        SystemClock.uptimeMillis());
2781                scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2782
2783                scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags
2784                        | PackageParser.PARSE_FORWARD_LOCK,
2785                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2786
2787                // Remove disable package settings for updated system apps that were
2788                // removed via an OTA. If the update is no longer present, remove the
2789                // app completely. Otherwise, revoke their system privileges.
2790                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2791                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2792                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2793                    final String msg;
2794                    if (deletedPkg == null) {
2795                        // should have found an update, but, we didn't; remove everything
2796                        msg = "Updated system package " + deletedAppName
2797                                + " no longer exists; removing its data";
2798                        // Actual deletion of code and data will be handled by later
2799                        // reconciliation step
2800                    } else {
2801                        // found an update; revoke system privileges
2802                        msg = "Updated system package + " + deletedAppName
2803                                + " no longer exists; revoking system privileges";
2804
2805                        // Don't do anything if a stub is removed from the system image. If
2806                        // we were to remove the uncompressed version from the /data partition,
2807                        // this is where it'd be done.
2808
2809                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2810                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2811                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2812                    }
2813                    logCriticalInfo(Log.WARN, msg);
2814                }
2815
2816                /*
2817                 * Make sure all system apps that we expected to appear on
2818                 * the userdata partition actually showed up. If they never
2819                 * appeared, crawl back and revive the system version.
2820                 */
2821                for (int i = 0; i < mExpectingBetter.size(); i++) {
2822                    final String packageName = mExpectingBetter.keyAt(i);
2823                    if (!mPackages.containsKey(packageName)) {
2824                        final File scanFile = mExpectingBetter.valueAt(i);
2825
2826                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2827                                + " but never showed up; reverting to system");
2828
2829                        final @ParseFlags int reparseFlags;
2830                        final @ScanFlags int rescanFlags;
2831                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2832                            reparseFlags =
2833                                    mDefParseFlags |
2834                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2835                            rescanFlags =
2836                                    scanFlags
2837                                    | SCAN_AS_SYSTEM
2838                                    | SCAN_AS_PRIVILEGED;
2839                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2840                            reparseFlags =
2841                                    mDefParseFlags |
2842                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2843                            rescanFlags =
2844                                    scanFlags
2845                                    | SCAN_AS_SYSTEM;
2846                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)) {
2847                            reparseFlags =
2848                                    mDefParseFlags |
2849                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2850                            rescanFlags =
2851                                    scanFlags
2852                                    | SCAN_AS_SYSTEM
2853                                    | SCAN_AS_VENDOR
2854                                    | SCAN_AS_PRIVILEGED;
2855                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2856                            reparseFlags =
2857                                    mDefParseFlags |
2858                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2859                            rescanFlags =
2860                                    scanFlags
2861                                    | SCAN_AS_SYSTEM
2862                                    | SCAN_AS_VENDOR;
2863                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2864                            reparseFlags =
2865                                    mDefParseFlags |
2866                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2867                            rescanFlags =
2868                                    scanFlags
2869                                    | SCAN_AS_SYSTEM
2870                                    | SCAN_AS_OEM;
2871                        } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) {
2872                            reparseFlags =
2873                                    mDefParseFlags |
2874                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2875                            rescanFlags =
2876                                    scanFlags
2877                                    | SCAN_AS_SYSTEM
2878                                    | SCAN_AS_PRODUCT
2879                                    | SCAN_AS_PRIVILEGED;
2880                        } else if (FileUtils.contains(productAppDir, scanFile)) {
2881                            reparseFlags =
2882                                    mDefParseFlags |
2883                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2884                            rescanFlags =
2885                                    scanFlags
2886                                    | SCAN_AS_SYSTEM
2887                                    | SCAN_AS_PRODUCT;
2888                        } else {
2889                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2890                            continue;
2891                        }
2892
2893                        mSettings.enableSystemPackageLPw(packageName);
2894
2895                        try {
2896                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2897                        } catch (PackageManagerException e) {
2898                            Slog.e(TAG, "Failed to parse original system package: "
2899                                    + e.getMessage());
2900                        }
2901                    }
2902                }
2903
2904                // Uncompress and install any stubbed system applications.
2905                // This must be done last to ensure all stubs are replaced or disabled.
2906                decompressSystemApplications(stubSystemApps, scanFlags);
2907
2908                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2909                                - cachedSystemApps;
2910
2911                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2912                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2913                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2914                        + " ms, packageCount: " + dataPackagesCount
2915                        + " , timePerPackage: "
2916                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2917                        + " , cached: " + cachedNonSystemApps);
2918                if (mIsUpgrade && dataPackagesCount > 0) {
2919                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2920                            ((int) dataScanTime) / dataPackagesCount);
2921                }
2922            }
2923            mExpectingBetter.clear();
2924
2925            // Resolve the storage manager.
2926            mStorageManagerPackage = getStorageManagerPackageName();
2927
2928            // Resolve protected action filters. Only the setup wizard is allowed to
2929            // have a high priority filter for these actions.
2930            mSetupWizardPackage = getSetupWizardPackageName();
2931            if (mProtectedFilters.size() > 0) {
2932                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2933                    Slog.i(TAG, "No setup wizard;"
2934                        + " All protected intents capped to priority 0");
2935                }
2936                for (ActivityIntentInfo filter : mProtectedFilters) {
2937                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2938                        if (DEBUG_FILTERS) {
2939                            Slog.i(TAG, "Found setup wizard;"
2940                                + " allow priority " + filter.getPriority() + ";"
2941                                + " package: " + filter.activity.info.packageName
2942                                + " activity: " + filter.activity.className
2943                                + " priority: " + filter.getPriority());
2944                        }
2945                        // skip setup wizard; allow it to keep the high priority filter
2946                        continue;
2947                    }
2948                    if (DEBUG_FILTERS) {
2949                        Slog.i(TAG, "Protected action; cap priority to 0;"
2950                                + " package: " + filter.activity.info.packageName
2951                                + " activity: " + filter.activity.className
2952                                + " origPrio: " + filter.getPriority());
2953                    }
2954                    filter.setPriority(0);
2955                }
2956            }
2957
2958            mSystemTextClassifierPackage = getSystemTextClassifierPackageName();
2959
2960            mDeferProtectedFilters = false;
2961            mProtectedFilters.clear();
2962
2963            // Now that we know all of the shared libraries, update all clients to have
2964            // the correct library paths.
2965            updateAllSharedLibrariesLPw(null);
2966
2967            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2968                // NOTE: We ignore potential failures here during a system scan (like
2969                // the rest of the commands above) because there's precious little we
2970                // can do about it. A settings error is reported, though.
2971                final List<String> changedAbiCodePath =
2972                        adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2973                if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
2974                    for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
2975                        final String codePathString = changedAbiCodePath.get(i);
2976                        try {
2977                            mInstaller.rmdex(codePathString,
2978                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
2979                        } catch (InstallerException ignored) {
2980                        }
2981                    }
2982                }
2983            }
2984
2985            // Now that we know all the packages we are keeping,
2986            // read and update their last usage times.
2987            mPackageUsage.read(mPackages);
2988            mCompilerStats.read();
2989
2990            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2991                    SystemClock.uptimeMillis());
2992            Slog.i(TAG, "Time to scan packages: "
2993                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2994                    + " seconds");
2995
2996            // If the platform SDK has changed since the last time we booted,
2997            // we need to re-grant app permission to catch any new ones that
2998            // appear.  This is really a hack, and means that apps can in some
2999            // cases get permissions that the user didn't initially explicitly
3000            // allow...  it would be nice to have some better way to handle
3001            // this situation.
3002            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
3003            if (sdkUpdated) {
3004                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
3005                        + mSdkVersion + "; regranting permissions for internal storage");
3006            }
3007            mPermissionManager.updateAllPermissions(
3008                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
3009                    mPermissionCallback);
3010            ver.sdkVersion = mSdkVersion;
3011
3012            // If this is the first boot or an update from pre-M, and it is a normal
3013            // boot, then we need to initialize the default preferred apps across
3014            // all defined users.
3015            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
3016                for (UserInfo user : sUserManager.getUsers(true)) {
3017                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
3018                    applyFactoryDefaultBrowserLPw(user.id);
3019                    primeDomainVerificationsLPw(user.id);
3020                }
3021            }
3022
3023            // Prepare storage for system user really early during boot,
3024            // since core system apps like SettingsProvider and SystemUI
3025            // can't wait for user to start
3026            final int storageFlags;
3027            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3028                storageFlags = StorageManager.FLAG_STORAGE_DE;
3029            } else {
3030                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
3031            }
3032            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
3033                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
3034                    true /* onlyCoreApps */);
3035            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
3036                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
3037                        Trace.TRACE_TAG_PACKAGE_MANAGER);
3038                traceLog.traceBegin("AppDataFixup");
3039                try {
3040                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
3041                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3042                } catch (InstallerException e) {
3043                    Slog.w(TAG, "Trouble fixing GIDs", e);
3044                }
3045                traceLog.traceEnd();
3046
3047                traceLog.traceBegin("AppDataPrepare");
3048                if (deferPackages == null || deferPackages.isEmpty()) {
3049                    return;
3050                }
3051                int count = 0;
3052                for (String pkgName : deferPackages) {
3053                    PackageParser.Package pkg = null;
3054                    synchronized (mPackages) {
3055                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
3056                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
3057                            pkg = ps.pkg;
3058                        }
3059                    }
3060                    if (pkg != null) {
3061                        synchronized (mInstallLock) {
3062                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
3063                                    true /* maybeMigrateAppData */);
3064                        }
3065                        count++;
3066                    }
3067                }
3068                traceLog.traceEnd();
3069                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3070            }, "prepareAppData");
3071
3072            // If this is first boot after an OTA, and a normal boot, then
3073            // we need to clear code cache directories.
3074            // Note that we do *not* clear the application profiles. These remain valid
3075            // across OTAs and are used to drive profile verification (post OTA) and
3076            // profile compilation (without waiting to collect a fresh set of profiles).
3077            if (mIsUpgrade && !onlyCore) {
3078                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3079                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3080                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3081                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3082                        // No apps are running this early, so no need to freeze
3083                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3084                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3085                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3086                    }
3087                }
3088                ver.fingerprint = Build.FINGERPRINT;
3089            }
3090
3091            checkDefaultBrowser();
3092
3093            // clear only after permissions and other defaults have been updated
3094            mExistingSystemPackages.clear();
3095            mPromoteSystemApps = false;
3096
3097            // All the changes are done during package scanning.
3098            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3099
3100            // can downgrade to reader
3101            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3102            mSettings.writeLPr();
3103            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3104            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3105                    SystemClock.uptimeMillis());
3106
3107            if (!mOnlyCore) {
3108                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3109                mRequiredInstallerPackage = getRequiredInstallerLPr();
3110                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3111                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3112                if (mIntentFilterVerifierComponent != null) {
3113                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3114                            mIntentFilterVerifierComponent);
3115                } else {
3116                    mIntentFilterVerifier = null;
3117                }
3118                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3119                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3120                        SharedLibraryInfo.VERSION_UNDEFINED);
3121                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3122                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3123                        SharedLibraryInfo.VERSION_UNDEFINED);
3124            } else {
3125                mRequiredVerifierPackage = null;
3126                mRequiredInstallerPackage = null;
3127                mRequiredUninstallerPackage = null;
3128                mIntentFilterVerifierComponent = null;
3129                mIntentFilterVerifier = null;
3130                mServicesSystemSharedLibraryPackageName = null;
3131                mSharedSystemSharedLibraryPackageName = null;
3132            }
3133
3134            mInstallerService = new PackageInstallerService(context, this);
3135            final Pair<ComponentName, String> instantAppResolverComponent =
3136                    getInstantAppResolverLPr();
3137            if (instantAppResolverComponent != null) {
3138                if (DEBUG_INSTANT) {
3139                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3140                }
3141                mInstantAppResolverConnection = new InstantAppResolverConnection(
3142                        mContext, instantAppResolverComponent.first,
3143                        instantAppResolverComponent.second);
3144                mInstantAppResolverSettingsComponent =
3145                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3146            } else {
3147                mInstantAppResolverConnection = null;
3148                mInstantAppResolverSettingsComponent = null;
3149            }
3150            updateInstantAppInstallerLocked(null);
3151
3152            // Read and update the usage of dex files.
3153            // Do this at the end of PM init so that all the packages have their
3154            // data directory reconciled.
3155            // At this point we know the code paths of the packages, so we can validate
3156            // the disk file and build the internal cache.
3157            // The usage file is expected to be small so loading and verifying it
3158            // should take a fairly small time compare to the other activities (e.g. package
3159            // scanning).
3160            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3161            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3162            for (int userId : currentUserIds) {
3163                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3164            }
3165            mDexManager.load(userPackages);
3166            if (mIsUpgrade) {
3167                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3168                        (int) (SystemClock.uptimeMillis() - startTime));
3169            }
3170        } // synchronized (mPackages)
3171        } // synchronized (mInstallLock)
3172
3173        // Now after opening every single application zip, make sure they
3174        // are all flushed.  Not really needed, but keeps things nice and
3175        // tidy.
3176        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3177        Runtime.getRuntime().gc();
3178        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3179
3180        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3181        FallbackCategoryProvider.loadFallbacks();
3182        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3183
3184        // The initial scanning above does many calls into installd while
3185        // holding the mPackages lock, but we're mostly interested in yelling
3186        // once we have a booted system.
3187        mInstaller.setWarnIfHeld(mPackages);
3188
3189        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3190    }
3191
3192    /**
3193     * Uncompress and install stub applications.
3194     * <p>In order to save space on the system partition, some applications are shipped in a
3195     * compressed form. In addition the compressed bits for the full application, the
3196     * system image contains a tiny stub comprised of only the Android manifest.
3197     * <p>During the first boot, attempt to uncompress and install the full application. If
3198     * the application can't be installed for any reason, disable the stub and prevent
3199     * uncompressing the full application during future boots.
3200     * <p>In order to forcefully attempt an installation of a full application, go to app
3201     * settings and enable the application.
3202     */
3203    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3204        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3205            final String pkgName = stubSystemApps.get(i);
3206            // skip if the system package is already disabled
3207            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3208                stubSystemApps.remove(i);
3209                continue;
3210            }
3211            // skip if the package isn't installed (?!); this should never happen
3212            final PackageParser.Package pkg = mPackages.get(pkgName);
3213            if (pkg == null) {
3214                stubSystemApps.remove(i);
3215                continue;
3216            }
3217            // skip if the package has been disabled by the user
3218            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3219            if (ps != null) {
3220                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3221                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3222                    stubSystemApps.remove(i);
3223                    continue;
3224                }
3225            }
3226
3227            if (DEBUG_COMPRESSION) {
3228                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3229            }
3230
3231            // uncompress the binary to its eventual destination on /data
3232            final File scanFile = decompressPackage(pkg);
3233            if (scanFile == null) {
3234                continue;
3235            }
3236
3237            // install the package to replace the stub on /system
3238            try {
3239                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3240                removePackageLI(pkg, true /*chatty*/);
3241                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3242                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3243                        UserHandle.USER_SYSTEM, "android");
3244                stubSystemApps.remove(i);
3245                continue;
3246            } catch (PackageManagerException e) {
3247                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3248            }
3249
3250            // any failed attempt to install the package will be cleaned up later
3251        }
3252
3253        // disable any stub still left; these failed to install the full application
3254        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3255            final String pkgName = stubSystemApps.get(i);
3256            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3257            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3258                    UserHandle.USER_SYSTEM, "android");
3259            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3260        }
3261    }
3262
3263    /**
3264     * Decompresses the given package on the system image onto
3265     * the /data partition.
3266     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3267     */
3268    private File decompressPackage(PackageParser.Package pkg) {
3269        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3270        if (compressedFiles == null || compressedFiles.length == 0) {
3271            if (DEBUG_COMPRESSION) {
3272                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3273            }
3274            return null;
3275        }
3276        final File dstCodePath =
3277                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3278        int ret = PackageManager.INSTALL_SUCCEEDED;
3279        try {
3280            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3281            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3282            for (File srcFile : compressedFiles) {
3283                final String srcFileName = srcFile.getName();
3284                final String dstFileName = srcFileName.substring(
3285                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3286                final File dstFile = new File(dstCodePath, dstFileName);
3287                ret = decompressFile(srcFile, dstFile);
3288                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3289                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3290                            + "; pkg: " + pkg.packageName
3291                            + ", file: " + dstFileName);
3292                    break;
3293                }
3294            }
3295        } catch (ErrnoException e) {
3296            logCriticalInfo(Log.ERROR, "Failed to decompress"
3297                    + "; pkg: " + pkg.packageName
3298                    + ", err: " + e.errno);
3299        }
3300        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3301            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3302            NativeLibraryHelper.Handle handle = null;
3303            try {
3304                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3305                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3306                        null /*abiOverride*/);
3307            } catch (IOException e) {
3308                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3309                        + "; pkg: " + pkg.packageName);
3310                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3311            } finally {
3312                IoUtils.closeQuietly(handle);
3313            }
3314        }
3315        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3316            if (dstCodePath == null || !dstCodePath.exists()) {
3317                return null;
3318            }
3319            removeCodePathLI(dstCodePath);
3320            return null;
3321        }
3322
3323        return dstCodePath;
3324    }
3325
3326    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3327        // we're only interested in updating the installer appliction when 1) it's not
3328        // already set or 2) the modified package is the installer
3329        if (mInstantAppInstallerActivity != null
3330                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3331                        .equals(modifiedPackage)) {
3332            return;
3333        }
3334        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3335    }
3336
3337    private static File preparePackageParserCache(boolean isUpgrade) {
3338        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3339            return null;
3340        }
3341
3342        // Disable package parsing on eng builds to allow for faster incremental development.
3343        if (Build.IS_ENG) {
3344            return null;
3345        }
3346
3347        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3348            Slog.i(TAG, "Disabling package parser cache due to system property.");
3349            return null;
3350        }
3351
3352        // The base directory for the package parser cache lives under /data/system/.
3353        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3354                "package_cache");
3355        if (cacheBaseDir == null) {
3356            return null;
3357        }
3358
3359        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3360        // This also serves to "GC" unused entries when the package cache version changes (which
3361        // can only happen during upgrades).
3362        if (isUpgrade) {
3363            FileUtils.deleteContents(cacheBaseDir);
3364        }
3365
3366
3367        // Return the versioned package cache directory. This is something like
3368        // "/data/system/package_cache/1"
3369        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3370
3371        if (cacheDir == null) {
3372            // Something went wrong. Attempt to delete everything and return.
3373            Slog.wtf(TAG, "Cache directory cannot be created - wiping base dir " + cacheBaseDir);
3374            FileUtils.deleteContentsAndDir(cacheBaseDir);
3375            return null;
3376        }
3377
3378        // The following is a workaround to aid development on non-numbered userdebug
3379        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3380        // the system partition is newer.
3381        //
3382        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3383        // that starts with "eng." to signify that this is an engineering build and not
3384        // destined for release.
3385        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3386            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3387
3388            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3389            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3390            // in general and should not be used for production changes. In this specific case,
3391            // we know that they will work.
3392            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3393            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3394                FileUtils.deleteContents(cacheBaseDir);
3395                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3396            }
3397        }
3398
3399        return cacheDir;
3400    }
3401
3402    @Override
3403    public boolean isFirstBoot() {
3404        // allow instant applications
3405        return mFirstBoot;
3406    }
3407
3408    @Override
3409    public boolean isOnlyCoreApps() {
3410        // allow instant applications
3411        return mOnlyCore;
3412    }
3413
3414    @Override
3415    public boolean isUpgrade() {
3416        // allow instant applications
3417        // The system property allows testing ota flow when upgraded to the same image.
3418        return mIsUpgrade || SystemProperties.getBoolean(
3419                "persist.pm.mock-upgrade", false /* default */);
3420    }
3421
3422    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3423        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3424
3425        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3426                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3427                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3428        if (matches.size() == 1) {
3429            return matches.get(0).getComponentInfo().packageName;
3430        } else if (matches.size() == 0) {
3431            Log.e(TAG, "There should probably be a verifier, but, none were found");
3432            return null;
3433        }
3434        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3435    }
3436
3437    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3438        synchronized (mPackages) {
3439            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3440            if (libraryEntry == null) {
3441                throw new IllegalStateException("Missing required shared library:" + name);
3442            }
3443            return libraryEntry.apk;
3444        }
3445    }
3446
3447    private @NonNull String getRequiredInstallerLPr() {
3448        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3449        intent.addCategory(Intent.CATEGORY_DEFAULT);
3450        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3451
3452        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3453                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3454                UserHandle.USER_SYSTEM);
3455        if (matches.size() == 1) {
3456            ResolveInfo resolveInfo = matches.get(0);
3457            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3458                throw new RuntimeException("The installer must be a privileged app");
3459            }
3460            return matches.get(0).getComponentInfo().packageName;
3461        } else {
3462            throw new RuntimeException("There must be exactly one installer; found " + matches);
3463        }
3464    }
3465
3466    private @NonNull String getRequiredUninstallerLPr() {
3467        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3468        intent.addCategory(Intent.CATEGORY_DEFAULT);
3469        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3470
3471        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3472                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3473                UserHandle.USER_SYSTEM);
3474        if (resolveInfo == null ||
3475                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3476            throw new RuntimeException("There must be exactly one uninstaller; found "
3477                    + resolveInfo);
3478        }
3479        return resolveInfo.getComponentInfo().packageName;
3480    }
3481
3482    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3483        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3484
3485        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3486                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3487                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3488        ResolveInfo best = null;
3489        final int N = matches.size();
3490        for (int i = 0; i < N; i++) {
3491            final ResolveInfo cur = matches.get(i);
3492            final String packageName = cur.getComponentInfo().packageName;
3493            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3494                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3495                continue;
3496            }
3497
3498            if (best == null || cur.priority > best.priority) {
3499                best = cur;
3500            }
3501        }
3502
3503        if (best != null) {
3504            return best.getComponentInfo().getComponentName();
3505        }
3506        Slog.w(TAG, "Intent filter verifier not found");
3507        return null;
3508    }
3509
3510    @Override
3511    public @Nullable ComponentName getInstantAppResolverComponent() {
3512        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3513            return null;
3514        }
3515        synchronized (mPackages) {
3516            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3517            if (instantAppResolver == null) {
3518                return null;
3519            }
3520            return instantAppResolver.first;
3521        }
3522    }
3523
3524    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3525        final String[] packageArray =
3526                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3527        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3528            if (DEBUG_INSTANT) {
3529                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3530            }
3531            return null;
3532        }
3533
3534        final int callingUid = Binder.getCallingUid();
3535        final int resolveFlags =
3536                MATCH_DIRECT_BOOT_AWARE
3537                | MATCH_DIRECT_BOOT_UNAWARE
3538                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3539        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3540        final Intent resolverIntent = new Intent(actionName);
3541        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3542                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3543        final int N = resolvers.size();
3544        if (N == 0) {
3545            if (DEBUG_INSTANT) {
3546                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3547            }
3548            return null;
3549        }
3550
3551        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3552        for (int i = 0; i < N; i++) {
3553            final ResolveInfo info = resolvers.get(i);
3554
3555            if (info.serviceInfo == null) {
3556                continue;
3557            }
3558
3559            final String packageName = info.serviceInfo.packageName;
3560            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3561                if (DEBUG_INSTANT) {
3562                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3563                            + " pkg: " + packageName + ", info:" + info);
3564                }
3565                continue;
3566            }
3567
3568            if (DEBUG_INSTANT) {
3569                Slog.v(TAG, "Ephemeral resolver found;"
3570                        + " pkg: " + packageName + ", info:" + info);
3571            }
3572            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3573        }
3574        if (DEBUG_INSTANT) {
3575            Slog.v(TAG, "Ephemeral resolver NOT found");
3576        }
3577        return null;
3578    }
3579
3580    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3581        String[] orderedActions = Build.IS_ENG
3582                ? new String[]{
3583                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST",
3584                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}
3585                : new String[]{
3586                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE};
3587
3588        final int resolveFlags =
3589                MATCH_DIRECT_BOOT_AWARE
3590                        | MATCH_DIRECT_BOOT_UNAWARE
3591                        | Intent.FLAG_IGNORE_EPHEMERAL
3592                        | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0);
3593        final Intent intent = new Intent();
3594        intent.addCategory(Intent.CATEGORY_DEFAULT);
3595        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3596        List<ResolveInfo> matches = null;
3597        for (String action : orderedActions) {
3598            intent.setAction(action);
3599            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3600                    resolveFlags, UserHandle.USER_SYSTEM);
3601            if (matches.isEmpty()) {
3602                if (DEBUG_INSTANT) {
3603                    Slog.d(TAG, "Instant App installer not found with " + action);
3604                }
3605            } else {
3606                break;
3607            }
3608        }
3609        Iterator<ResolveInfo> iter = matches.iterator();
3610        while (iter.hasNext()) {
3611            final ResolveInfo rInfo = iter.next();
3612            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3613            if (ps != null) {
3614                final PermissionsState permissionsState = ps.getPermissionsState();
3615                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)
3616                        || Build.IS_ENG) {
3617                    continue;
3618                }
3619            }
3620            iter.remove();
3621        }
3622        if (matches.size() == 0) {
3623            return null;
3624        } else if (matches.size() == 1) {
3625            return (ActivityInfo) matches.get(0).getComponentInfo();
3626        } else {
3627            throw new RuntimeException(
3628                    "There must be at most one ephemeral installer; found " + matches);
3629        }
3630    }
3631
3632    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3633            @NonNull ComponentName resolver) {
3634        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3635                .addCategory(Intent.CATEGORY_DEFAULT)
3636                .setPackage(resolver.getPackageName());
3637        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3638        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3639                UserHandle.USER_SYSTEM);
3640        if (matches.isEmpty()) {
3641            return null;
3642        }
3643        return matches.get(0).getComponentInfo().getComponentName();
3644    }
3645
3646    private void primeDomainVerificationsLPw(int userId) {
3647        if (DEBUG_DOMAIN_VERIFICATION) {
3648            Slog.d(TAG, "Priming domain verifications in user " + userId);
3649        }
3650
3651        SystemConfig systemConfig = SystemConfig.getInstance();
3652        ArraySet<String> packages = systemConfig.getLinkedApps();
3653
3654        for (String packageName : packages) {
3655            PackageParser.Package pkg = mPackages.get(packageName);
3656            if (pkg != null) {
3657                if (!pkg.isSystem()) {
3658                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3659                    continue;
3660                }
3661
3662                ArraySet<String> domains = null;
3663                for (PackageParser.Activity a : pkg.activities) {
3664                    for (ActivityIntentInfo filter : a.intents) {
3665                        if (hasValidDomains(filter)) {
3666                            if (domains == null) {
3667                                domains = new ArraySet<String>();
3668                            }
3669                            domains.addAll(filter.getHostsList());
3670                        }
3671                    }
3672                }
3673
3674                if (domains != null && domains.size() > 0) {
3675                    if (DEBUG_DOMAIN_VERIFICATION) {
3676                        Slog.v(TAG, "      + " + packageName);
3677                    }
3678                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3679                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3680                    // and then 'always' in the per-user state actually used for intent resolution.
3681                    final IntentFilterVerificationInfo ivi;
3682                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3683                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3684                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3685                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3686                } else {
3687                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3688                            + "' does not handle web links");
3689                }
3690            } else {
3691                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3692            }
3693        }
3694
3695        scheduleWritePackageRestrictionsLocked(userId);
3696        scheduleWriteSettingsLocked();
3697    }
3698
3699    private void applyFactoryDefaultBrowserLPw(int userId) {
3700        // The default browser app's package name is stored in a string resource,
3701        // with a product-specific overlay used for vendor customization.
3702        String browserPkg = mContext.getResources().getString(
3703                com.android.internal.R.string.default_browser);
3704        if (!TextUtils.isEmpty(browserPkg)) {
3705            // non-empty string => required to be a known package
3706            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3707            if (ps == null) {
3708                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3709                browserPkg = null;
3710            } else {
3711                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3712            }
3713        }
3714
3715        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3716        // default.  If there's more than one, just leave everything alone.
3717        if (browserPkg == null) {
3718            calculateDefaultBrowserLPw(userId);
3719        }
3720    }
3721
3722    private void calculateDefaultBrowserLPw(int userId) {
3723        List<String> allBrowsers = resolveAllBrowserApps(userId);
3724        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3725        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3726    }
3727
3728    private List<String> resolveAllBrowserApps(int userId) {
3729        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3730        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3731                PackageManager.MATCH_ALL, userId);
3732
3733        final int count = list.size();
3734        List<String> result = new ArrayList<String>(count);
3735        for (int i=0; i<count; i++) {
3736            ResolveInfo info = list.get(i);
3737            if (info.activityInfo == null
3738                    || !info.handleAllWebDataURI
3739                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3740                    || result.contains(info.activityInfo.packageName)) {
3741                continue;
3742            }
3743            result.add(info.activityInfo.packageName);
3744        }
3745
3746        return result;
3747    }
3748
3749    private boolean packageIsBrowser(String packageName, int userId) {
3750        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3751                PackageManager.MATCH_ALL, userId);
3752        final int N = list.size();
3753        for (int i = 0; i < N; i++) {
3754            ResolveInfo info = list.get(i);
3755            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3756                return true;
3757            }
3758        }
3759        return false;
3760    }
3761
3762    private void checkDefaultBrowser() {
3763        final int myUserId = UserHandle.myUserId();
3764        final String packageName = getDefaultBrowserPackageName(myUserId);
3765        if (packageName != null) {
3766            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3767            if (info == null) {
3768                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3769                synchronized (mPackages) {
3770                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3771                }
3772            }
3773        }
3774    }
3775
3776    @Override
3777    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3778            throws RemoteException {
3779        try {
3780            return super.onTransact(code, data, reply, flags);
3781        } catch (RuntimeException e) {
3782            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3783                Slog.wtf(TAG, "Package Manager Crash", e);
3784            }
3785            throw e;
3786        }
3787    }
3788
3789    static int[] appendInts(int[] cur, int[] add) {
3790        if (add == null) return cur;
3791        if (cur == null) return add;
3792        final int N = add.length;
3793        for (int i=0; i<N; i++) {
3794            cur = appendInt(cur, add[i]);
3795        }
3796        return cur;
3797    }
3798
3799    /**
3800     * Returns whether or not a full application can see an instant application.
3801     * <p>
3802     * Currently, there are three cases in which this can occur:
3803     * <ol>
3804     * <li>The calling application is a "special" process. Special processes
3805     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3806     * <li>The calling application has the permission
3807     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3808     * <li>The calling application is the default launcher on the
3809     *     system partition.</li>
3810     * </ol>
3811     */
3812    private boolean canViewInstantApps(int callingUid, int userId) {
3813        if (callingUid < Process.FIRST_APPLICATION_UID) {
3814            return true;
3815        }
3816        if (mContext.checkCallingOrSelfPermission(
3817                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3818            return true;
3819        }
3820        if (mContext.checkCallingOrSelfPermission(
3821                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3822            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3823            if (homeComponent != null
3824                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3825                return true;
3826            }
3827        }
3828        return false;
3829    }
3830
3831    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3832        if (!sUserManager.exists(userId)) return null;
3833        if (ps == null) {
3834            return null;
3835        }
3836        final int callingUid = Binder.getCallingUid();
3837        // Filter out ephemeral app metadata:
3838        //   * The system/shell/root can see metadata for any app
3839        //   * An installed app can see metadata for 1) other installed apps
3840        //     and 2) ephemeral apps that have explicitly interacted with it
3841        //   * Ephemeral apps can only see their own data and exposed installed apps
3842        //   * Holding a signature permission allows seeing instant apps
3843        if (filterAppAccessLPr(ps, callingUid, userId)) {
3844            return null;
3845        }
3846
3847        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3848                && ps.isSystem()) {
3849            flags |= MATCH_ANY_USER;
3850        }
3851
3852        final PackageUserState state = ps.readUserState(userId);
3853        PackageParser.Package p = ps.pkg;
3854        if (p != null) {
3855            final PermissionsState permissionsState = ps.getPermissionsState();
3856
3857            // Compute GIDs only if requested
3858            final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3859                    ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3860            // Compute granted permissions only if package has requested permissions
3861            final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3862                    ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3863
3864            PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3865                    ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3866
3867            if (packageInfo == null) {
3868                return null;
3869            }
3870
3871            packageInfo.packageName = packageInfo.applicationInfo.packageName =
3872                    resolveExternalPackageNameLPr(p);
3873
3874            return packageInfo;
3875        } else if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 && state.isAvailable(flags)) {
3876            PackageInfo pi = new PackageInfo();
3877            pi.packageName = ps.name;
3878            pi.setLongVersionCode(ps.versionCode);
3879            pi.sharedUserId = (ps.sharedUser != null) ? ps.sharedUser.name : null;
3880            pi.firstInstallTime = ps.firstInstallTime;
3881            pi.lastUpdateTime = ps.lastUpdateTime;
3882
3883            ApplicationInfo ai = new ApplicationInfo();
3884            ai.packageName = ps.name;
3885            ai.uid = UserHandle.getUid(userId, ps.appId);
3886            ai.primaryCpuAbi = ps.primaryCpuAbiString;
3887            ai.secondaryCpuAbi = ps.secondaryCpuAbiString;
3888            ai.versionCode = ps.versionCode;
3889            ai.flags = ps.pkgFlags;
3890            ai.privateFlags = ps.pkgPrivateFlags;
3891            pi.applicationInfo = PackageParser.generateApplicationInfo(ai, flags, state, userId);
3892
3893            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "ps.pkg is n/a for ["
3894                    + ps.name + "]. Provides a minimum info.");
3895            return pi;
3896        } else {
3897            return null;
3898        }
3899    }
3900
3901    @Override
3902    public void checkPackageStartable(String packageName, int userId) {
3903        final int callingUid = Binder.getCallingUid();
3904        if (getInstantAppPackageName(callingUid) != null) {
3905            throw new SecurityException("Instant applications don't have access to this method");
3906        }
3907        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3908        synchronized (mPackages) {
3909            final PackageSetting ps = mSettings.mPackages.get(packageName);
3910            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3911                throw new SecurityException("Package " + packageName + " was not found!");
3912            }
3913
3914            if (!ps.getInstalled(userId)) {
3915                throw new SecurityException(
3916                        "Package " + packageName + " was not installed for user " + userId + "!");
3917            }
3918
3919            if (mSafeMode && !ps.isSystem()) {
3920                throw new SecurityException("Package " + packageName + " not a system app!");
3921            }
3922
3923            if (mFrozenPackages.contains(packageName)) {
3924                throw new SecurityException("Package " + packageName + " is currently frozen!");
3925            }
3926
3927            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3928                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3929            }
3930        }
3931    }
3932
3933    @Override
3934    public boolean isPackageAvailable(String packageName, int userId) {
3935        if (!sUserManager.exists(userId)) return false;
3936        final int callingUid = Binder.getCallingUid();
3937        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3938                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3939        synchronized (mPackages) {
3940            PackageParser.Package p = mPackages.get(packageName);
3941            if (p != null) {
3942                final PackageSetting ps = (PackageSetting) p.mExtras;
3943                if (filterAppAccessLPr(ps, callingUid, userId)) {
3944                    return false;
3945                }
3946                if (ps != null) {
3947                    final PackageUserState state = ps.readUserState(userId);
3948                    if (state != null) {
3949                        return PackageParser.isAvailable(state);
3950                    }
3951                }
3952            }
3953        }
3954        return false;
3955    }
3956
3957    @Override
3958    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3959        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3960                flags, Binder.getCallingUid(), userId);
3961    }
3962
3963    @Override
3964    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3965            int flags, int userId) {
3966        return getPackageInfoInternal(versionedPackage.getPackageName(),
3967                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
3968    }
3969
3970    /**
3971     * Important: The provided filterCallingUid is used exclusively to filter out packages
3972     * that can be seen based on user state. It's typically the original caller uid prior
3973     * to clearing. Because it can only be provided by trusted code, it's value can be
3974     * trusted and will be used as-is; unlike userId which will be validated by this method.
3975     */
3976    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
3977            int flags, int filterCallingUid, int userId) {
3978        if (!sUserManager.exists(userId)) return null;
3979        flags = updateFlagsForPackage(flags, userId, packageName);
3980        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
3981                false /* requireFullPermission */, false /* checkShell */, "get package info");
3982
3983        // reader
3984        synchronized (mPackages) {
3985            // Normalize package name to handle renamed packages and static libs
3986            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3987
3988            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3989            if (matchFactoryOnly) {
3990                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3991                if (ps != null) {
3992                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3993                        return null;
3994                    }
3995                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3996                        return null;
3997                    }
3998                    return generatePackageInfo(ps, flags, userId);
3999                }
4000            }
4001
4002            PackageParser.Package p = mPackages.get(packageName);
4003            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
4004                return null;
4005            }
4006            if (DEBUG_PACKAGE_INFO)
4007                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
4008            if (p != null) {
4009                final PackageSetting ps = (PackageSetting) p.mExtras;
4010                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4011                    return null;
4012                }
4013                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
4014                    return null;
4015                }
4016                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4017            }
4018            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4019                final PackageSetting ps = mSettings.mPackages.get(packageName);
4020                if (ps == null) return null;
4021                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4022                    return null;
4023                }
4024                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4025                    return null;
4026                }
4027                return generatePackageInfo(ps, flags, userId);
4028            }
4029        }
4030        return null;
4031    }
4032
4033    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4034        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4035            return true;
4036        }
4037        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4038            return true;
4039        }
4040        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4041            return true;
4042        }
4043        return false;
4044    }
4045
4046    private boolean isComponentVisibleToInstantApp(
4047            @Nullable ComponentName component, @ComponentType int type) {
4048        if (type == TYPE_ACTIVITY) {
4049            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4050            return activity != null
4051                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4052                    : false;
4053        } else if (type == TYPE_RECEIVER) {
4054            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4055            return activity != null
4056                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4057                    : false;
4058        } else if (type == TYPE_SERVICE) {
4059            final PackageParser.Service service = mServices.mServices.get(component);
4060            return service != null
4061                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4062                    : false;
4063        } else if (type == TYPE_PROVIDER) {
4064            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4065            return provider != null
4066                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4067                    : false;
4068        } else if (type == TYPE_UNKNOWN) {
4069            return isComponentVisibleToInstantApp(component);
4070        }
4071        return false;
4072    }
4073
4074    /**
4075     * Returns whether or not access to the application should be filtered.
4076     * <p>
4077     * Access may be limited based upon whether the calling or target applications
4078     * are instant applications.
4079     *
4080     * @see #canAccessInstantApps(int)
4081     */
4082    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4083            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4084        // if we're in an isolated process, get the real calling UID
4085        if (Process.isIsolated(callingUid)) {
4086            callingUid = mIsolatedOwners.get(callingUid);
4087        }
4088        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4089        final boolean callerIsInstantApp = instantAppPkgName != null;
4090        if (ps == null) {
4091            if (callerIsInstantApp) {
4092                // pretend the application exists, but, needs to be filtered
4093                return true;
4094            }
4095            return false;
4096        }
4097        // if the target and caller are the same application, don't filter
4098        if (isCallerSameApp(ps.name, callingUid)) {
4099            return false;
4100        }
4101        if (callerIsInstantApp) {
4102            // request for a specific component; if it hasn't been explicitly exposed through
4103            // property or instrumentation target, filter
4104            if (component != null) {
4105                final PackageParser.Instrumentation instrumentation =
4106                        mInstrumentation.get(component);
4107                if (instrumentation != null
4108                        && isCallerSameApp(instrumentation.info.targetPackage, callingUid)) {
4109                    return false;
4110                }
4111                return !isComponentVisibleToInstantApp(component, componentType);
4112            }
4113            // request for application; if no components have been explicitly exposed, filter
4114            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4115        }
4116        if (ps.getInstantApp(userId)) {
4117            // caller can see all components of all instant applications, don't filter
4118            if (canViewInstantApps(callingUid, userId)) {
4119                return false;
4120            }
4121            // request for a specific instant application component, filter
4122            if (component != null) {
4123                return true;
4124            }
4125            // request for an instant application; if the caller hasn't been granted access, filter
4126            return !mInstantAppRegistry.isInstantAccessGranted(
4127                    userId, UserHandle.getAppId(callingUid), ps.appId);
4128        }
4129        return false;
4130    }
4131
4132    /**
4133     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4134     */
4135    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4136        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4137    }
4138
4139    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4140            int flags) {
4141        // Callers can access only the libs they depend on, otherwise they need to explicitly
4142        // ask for the shared libraries given the caller is allowed to access all static libs.
4143        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4144            // System/shell/root get to see all static libs
4145            final int appId = UserHandle.getAppId(uid);
4146            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4147                    || appId == Process.ROOT_UID) {
4148                return false;
4149            }
4150        }
4151
4152        // No package means no static lib as it is always on internal storage
4153        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4154            return false;
4155        }
4156
4157        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4158                ps.pkg.staticSharedLibVersion);
4159        if (libEntry == null) {
4160            return false;
4161        }
4162
4163        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4164        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4165        if (uidPackageNames == null) {
4166            return true;
4167        }
4168
4169        for (String uidPackageName : uidPackageNames) {
4170            if (ps.name.equals(uidPackageName)) {
4171                return false;
4172            }
4173            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4174            if (uidPs != null) {
4175                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4176                        libEntry.info.getName());
4177                if (index < 0) {
4178                    continue;
4179                }
4180                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4181                    return false;
4182                }
4183            }
4184        }
4185        return true;
4186    }
4187
4188    @Override
4189    public String[] currentToCanonicalPackageNames(String[] names) {
4190        final int callingUid = Binder.getCallingUid();
4191        if (getInstantAppPackageName(callingUid) != null) {
4192            return names;
4193        }
4194        final String[] out = new String[names.length];
4195        // reader
4196        synchronized (mPackages) {
4197            final int callingUserId = UserHandle.getUserId(callingUid);
4198            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4199            for (int i=names.length-1; i>=0; i--) {
4200                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4201                boolean translateName = false;
4202                if (ps != null && ps.realName != null) {
4203                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4204                    translateName = !targetIsInstantApp
4205                            || canViewInstantApps
4206                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4207                                    UserHandle.getAppId(callingUid), ps.appId);
4208                }
4209                out[i] = translateName ? ps.realName : names[i];
4210            }
4211        }
4212        return out;
4213    }
4214
4215    @Override
4216    public String[] canonicalToCurrentPackageNames(String[] names) {
4217        final int callingUid = Binder.getCallingUid();
4218        if (getInstantAppPackageName(callingUid) != null) {
4219            return names;
4220        }
4221        final String[] out = new String[names.length];
4222        // reader
4223        synchronized (mPackages) {
4224            final int callingUserId = UserHandle.getUserId(callingUid);
4225            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4226            for (int i=names.length-1; i>=0; i--) {
4227                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4228                boolean translateName = false;
4229                if (cur != null) {
4230                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4231                    final boolean targetIsInstantApp =
4232                            ps != null && ps.getInstantApp(callingUserId);
4233                    translateName = !targetIsInstantApp
4234                            || canViewInstantApps
4235                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4236                                    UserHandle.getAppId(callingUid), ps.appId);
4237                }
4238                out[i] = translateName ? cur : names[i];
4239            }
4240        }
4241        return out;
4242    }
4243
4244    @Override
4245    public int getPackageUid(String packageName, int flags, int userId) {
4246        if (!sUserManager.exists(userId)) return -1;
4247        final int callingUid = Binder.getCallingUid();
4248        flags = updateFlagsForPackage(flags, userId, packageName);
4249        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4250                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4251
4252        // reader
4253        synchronized (mPackages) {
4254            final PackageParser.Package p = mPackages.get(packageName);
4255            if (p != null && p.isMatch(flags)) {
4256                PackageSetting ps = (PackageSetting) p.mExtras;
4257                if (filterAppAccessLPr(ps, callingUid, userId)) {
4258                    return -1;
4259                }
4260                return UserHandle.getUid(userId, p.applicationInfo.uid);
4261            }
4262            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4263                final PackageSetting ps = mSettings.mPackages.get(packageName);
4264                if (ps != null && ps.isMatch(flags)
4265                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4266                    return UserHandle.getUid(userId, ps.appId);
4267                }
4268            }
4269        }
4270
4271        return -1;
4272    }
4273
4274    @Override
4275    public int[] getPackageGids(String packageName, int flags, int userId) {
4276        if (!sUserManager.exists(userId)) return null;
4277        final int callingUid = Binder.getCallingUid();
4278        flags = updateFlagsForPackage(flags, userId, packageName);
4279        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4280                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4281
4282        // reader
4283        synchronized (mPackages) {
4284            final PackageParser.Package p = mPackages.get(packageName);
4285            if (p != null && p.isMatch(flags)) {
4286                PackageSetting ps = (PackageSetting) p.mExtras;
4287                if (filterAppAccessLPr(ps, callingUid, userId)) {
4288                    return null;
4289                }
4290                // TODO: Shouldn't this be checking for package installed state for userId and
4291                // return null?
4292                return ps.getPermissionsState().computeGids(userId);
4293            }
4294            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4295                final PackageSetting ps = mSettings.mPackages.get(packageName);
4296                if (ps != null && ps.isMatch(flags)
4297                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4298                    return ps.getPermissionsState().computeGids(userId);
4299                }
4300            }
4301        }
4302
4303        return null;
4304    }
4305
4306    @Override
4307    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4308        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4309    }
4310
4311    @Override
4312    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4313            int flags) {
4314        final List<PermissionInfo> permissionList =
4315                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4316        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4317    }
4318
4319    @Override
4320    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4321        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4322    }
4323
4324    @Override
4325    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4326        final List<PermissionGroupInfo> permissionList =
4327                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4328        return (permissionList == null)
4329                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4330    }
4331
4332    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4333            int filterCallingUid, int userId) {
4334        if (!sUserManager.exists(userId)) return null;
4335        PackageSetting ps = mSettings.mPackages.get(packageName);
4336        if (ps != null) {
4337            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4338                return null;
4339            }
4340            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4341                return null;
4342            }
4343            if (ps.pkg == null) {
4344                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4345                if (pInfo != null) {
4346                    return pInfo.applicationInfo;
4347                }
4348                return null;
4349            }
4350            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4351                    ps.readUserState(userId), userId);
4352            if (ai != null) {
4353                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4354            }
4355            return ai;
4356        }
4357        return null;
4358    }
4359
4360    @Override
4361    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4362        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4363    }
4364
4365    /**
4366     * Important: The provided filterCallingUid is used exclusively to filter out applications
4367     * that can be seen based on user state. It's typically the original caller uid prior
4368     * to clearing. Because it can only be provided by trusted code, it's value can be
4369     * trusted and will be used as-is; unlike userId which will be validated by this method.
4370     */
4371    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4372            int filterCallingUid, int userId) {
4373        if (!sUserManager.exists(userId)) return null;
4374        flags = updateFlagsForApplication(flags, userId, packageName);
4375        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4376                false /* requireFullPermission */, false /* checkShell */, "get application info");
4377
4378        // writer
4379        synchronized (mPackages) {
4380            // Normalize package name to handle renamed packages and static libs
4381            packageName = resolveInternalPackageNameLPr(packageName,
4382                    PackageManager.VERSION_CODE_HIGHEST);
4383
4384            PackageParser.Package p = mPackages.get(packageName);
4385            if (DEBUG_PACKAGE_INFO) Log.v(
4386                    TAG, "getApplicationInfo " + packageName
4387                    + ": " + p);
4388            if (p != null) {
4389                PackageSetting ps = mSettings.mPackages.get(packageName);
4390                if (ps == null) return null;
4391                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4392                    return null;
4393                }
4394                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4395                    return null;
4396                }
4397                // Note: isEnabledLP() does not apply here - always return info
4398                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4399                        p, flags, ps.readUserState(userId), userId);
4400                if (ai != null) {
4401                    ai.packageName = resolveExternalPackageNameLPr(p);
4402                }
4403                return ai;
4404            }
4405            if ("android".equals(packageName)||"system".equals(packageName)) {
4406                return mAndroidApplication;
4407            }
4408            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4409                // Already generates the external package name
4410                return generateApplicationInfoFromSettingsLPw(packageName,
4411                        flags, filterCallingUid, userId);
4412            }
4413        }
4414        return null;
4415    }
4416
4417    private String normalizePackageNameLPr(String packageName) {
4418        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4419        return normalizedPackageName != null ? normalizedPackageName : packageName;
4420    }
4421
4422    @Override
4423    public void deletePreloadsFileCache() {
4424        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4425            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4426        }
4427        File dir = Environment.getDataPreloadsFileCacheDirectory();
4428        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4429        FileUtils.deleteContents(dir);
4430    }
4431
4432    @Override
4433    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4434            final int storageFlags, final IPackageDataObserver observer) {
4435        mContext.enforceCallingOrSelfPermission(
4436                android.Manifest.permission.CLEAR_APP_CACHE, null);
4437        mHandler.post(() -> {
4438            boolean success = false;
4439            try {
4440                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4441                success = true;
4442            } catch (IOException e) {
4443                Slog.w(TAG, e);
4444            }
4445            if (observer != null) {
4446                try {
4447                    observer.onRemoveCompleted(null, success);
4448                } catch (RemoteException e) {
4449                    Slog.w(TAG, e);
4450                }
4451            }
4452        });
4453    }
4454
4455    @Override
4456    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4457            final int storageFlags, final IntentSender pi) {
4458        mContext.enforceCallingOrSelfPermission(
4459                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4460        mHandler.post(() -> {
4461            boolean success = false;
4462            try {
4463                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4464                success = true;
4465            } catch (IOException e) {
4466                Slog.w(TAG, e);
4467            }
4468            if (pi != null) {
4469                try {
4470                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4471                } catch (SendIntentException e) {
4472                    Slog.w(TAG, e);
4473                }
4474            }
4475        });
4476    }
4477
4478    /**
4479     * Blocking call to clear various types of cached data across the system
4480     * until the requested bytes are available.
4481     */
4482    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4483        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4484        final File file = storage.findPathForUuid(volumeUuid);
4485        if (file.getUsableSpace() >= bytes) return;
4486
4487        if (ENABLE_FREE_CACHE_V2) {
4488            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4489                    volumeUuid);
4490            final boolean aggressive = (storageFlags
4491                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4492            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4493
4494            // 1. Pre-flight to determine if we have any chance to succeed
4495            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4496            if (internalVolume && (aggressive || SystemProperties
4497                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4498                deletePreloadsFileCache();
4499                if (file.getUsableSpace() >= bytes) return;
4500            }
4501
4502            // 3. Consider parsed APK data (aggressive only)
4503            if (internalVolume && aggressive) {
4504                FileUtils.deleteContents(mCacheDir);
4505                if (file.getUsableSpace() >= bytes) return;
4506            }
4507
4508            // 4. Consider cached app data (above quotas)
4509            try {
4510                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4511                        Installer.FLAG_FREE_CACHE_V2);
4512            } catch (InstallerException ignored) {
4513            }
4514            if (file.getUsableSpace() >= bytes) return;
4515
4516            // 5. Consider shared libraries with refcount=0 and age>min cache period
4517            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4518                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4519                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4520                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4521                return;
4522            }
4523
4524            // 6. Consider dexopt output (aggressive only)
4525            // TODO: Implement
4526
4527            // 7. Consider installed instant apps unused longer than min cache period
4528            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4529                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4530                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4531                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4532                return;
4533            }
4534
4535            // 8. Consider cached app data (below quotas)
4536            try {
4537                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4538                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4539            } catch (InstallerException ignored) {
4540            }
4541            if (file.getUsableSpace() >= bytes) return;
4542
4543            // 9. Consider DropBox entries
4544            // TODO: Implement
4545
4546            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4547            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4548                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4549                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4550                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4551                return;
4552            }
4553        } else {
4554            try {
4555                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4556            } catch (InstallerException ignored) {
4557            }
4558            if (file.getUsableSpace() >= bytes) return;
4559        }
4560
4561        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4562    }
4563
4564    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4565            throws IOException {
4566        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4567        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4568
4569        List<VersionedPackage> packagesToDelete = null;
4570        final long now = System.currentTimeMillis();
4571
4572        synchronized (mPackages) {
4573            final int[] allUsers = sUserManager.getUserIds();
4574            final int libCount = mSharedLibraries.size();
4575            for (int i = 0; i < libCount; i++) {
4576                final LongSparseArray<SharedLibraryEntry> versionedLib
4577                        = mSharedLibraries.valueAt(i);
4578                if (versionedLib == null) {
4579                    continue;
4580                }
4581                final int versionCount = versionedLib.size();
4582                for (int j = 0; j < versionCount; j++) {
4583                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4584                    // Skip packages that are not static shared libs.
4585                    if (!libInfo.isStatic()) {
4586                        break;
4587                    }
4588                    // Important: We skip static shared libs used for some user since
4589                    // in such a case we need to keep the APK on the device. The check for
4590                    // a lib being used for any user is performed by the uninstall call.
4591                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4592                    // Resolve the package name - we use synthetic package names internally
4593                    final String internalPackageName = resolveInternalPackageNameLPr(
4594                            declaringPackage.getPackageName(),
4595                            declaringPackage.getLongVersionCode());
4596                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4597                    // Skip unused static shared libs cached less than the min period
4598                    // to prevent pruning a lib needed by a subsequently installed package.
4599                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4600                        continue;
4601                    }
4602                    if (packagesToDelete == null) {
4603                        packagesToDelete = new ArrayList<>();
4604                    }
4605                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4606                            declaringPackage.getLongVersionCode()));
4607                }
4608            }
4609        }
4610
4611        if (packagesToDelete != null) {
4612            final int packageCount = packagesToDelete.size();
4613            for (int i = 0; i < packageCount; i++) {
4614                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4615                // Delete the package synchronously (will fail of the lib used for any user).
4616                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4617                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4618                                == PackageManager.DELETE_SUCCEEDED) {
4619                    if (volume.getUsableSpace() >= neededSpace) {
4620                        return true;
4621                    }
4622                }
4623            }
4624        }
4625
4626        return false;
4627    }
4628
4629    /**
4630     * Update given flags based on encryption status of current user.
4631     */
4632    private int updateFlags(int flags, int userId) {
4633        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4634                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4635            // Caller expressed an explicit opinion about what encryption
4636            // aware/unaware components they want to see, so fall through and
4637            // give them what they want
4638        } else {
4639            // Caller expressed no opinion, so match based on user state
4640            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4641                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4642            } else {
4643                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4644            }
4645        }
4646        return flags;
4647    }
4648
4649    private UserManagerInternal getUserManagerInternal() {
4650        if (mUserManagerInternal == null) {
4651            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4652        }
4653        return mUserManagerInternal;
4654    }
4655
4656    private ActivityManagerInternal getActivityManagerInternal() {
4657        if (mActivityManagerInternal == null) {
4658            mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
4659        }
4660        return mActivityManagerInternal;
4661    }
4662
4663
4664    private DeviceIdleController.LocalService getDeviceIdleController() {
4665        if (mDeviceIdleController == null) {
4666            mDeviceIdleController =
4667                    LocalServices.getService(DeviceIdleController.LocalService.class);
4668        }
4669        return mDeviceIdleController;
4670    }
4671
4672    /**
4673     * Update given flags when being used to request {@link PackageInfo}.
4674     */
4675    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4676        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4677        boolean triaged = true;
4678        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4679                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4680            // Caller is asking for component details, so they'd better be
4681            // asking for specific encryption matching behavior, or be triaged
4682            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4683                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4684                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4685                triaged = false;
4686            }
4687        }
4688        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4689                | PackageManager.MATCH_SYSTEM_ONLY
4690                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4691            triaged = false;
4692        }
4693        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4694            mPermissionManager.enforceCrossUserPermission(
4695                    Binder.getCallingUid(), userId, false, false,
4696                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4697                    + Debug.getCallers(5));
4698        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4699                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4700            // If the caller wants all packages and has a restricted profile associated with it,
4701            // then match all users. This is to make sure that launchers that need to access work
4702            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4703            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4704            flags |= PackageManager.MATCH_ANY_USER;
4705        }
4706        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4707            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4708                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4709        }
4710        return updateFlags(flags, userId);
4711    }
4712
4713    /**
4714     * Update given flags when being used to request {@link ApplicationInfo}.
4715     */
4716    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4717        return updateFlagsForPackage(flags, userId, cookie);
4718    }
4719
4720    /**
4721     * Update given flags when being used to request {@link ComponentInfo}.
4722     */
4723    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4724        if (cookie instanceof Intent) {
4725            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4726                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4727            }
4728        }
4729
4730        boolean triaged = true;
4731        // Caller is asking for component details, so they'd better be
4732        // asking for specific encryption matching behavior, or be triaged
4733        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4734                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4735                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4736            triaged = false;
4737        }
4738        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4739            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4740                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4741        }
4742
4743        return updateFlags(flags, userId);
4744    }
4745
4746    /**
4747     * Update given intent when being used to request {@link ResolveInfo}.
4748     */
4749    private Intent updateIntentForResolve(Intent intent) {
4750        if (intent.getSelector() != null) {
4751            intent = intent.getSelector();
4752        }
4753        if (DEBUG_PREFERRED) {
4754            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4755        }
4756        return intent;
4757    }
4758
4759    /**
4760     * Update given flags when being used to request {@link ResolveInfo}.
4761     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4762     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4763     * flag set. However, this flag is only honoured in three circumstances:
4764     * <ul>
4765     * <li>when called from a system process</li>
4766     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4767     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4768     * action and a {@code android.intent.category.BROWSABLE} category</li>
4769     * </ul>
4770     */
4771    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4772        return updateFlagsForResolve(flags, userId, intent, callingUid,
4773                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4774    }
4775    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4776            boolean wantInstantApps) {
4777        return updateFlagsForResolve(flags, userId, intent, callingUid,
4778                wantInstantApps, false /*onlyExposedExplicitly*/);
4779    }
4780    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4781            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4782        // Safe mode means we shouldn't match any third-party components
4783        if (mSafeMode) {
4784            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4785        }
4786        if (getInstantAppPackageName(callingUid) != null) {
4787            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4788            if (onlyExposedExplicitly) {
4789                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4790            }
4791            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4792            flags |= PackageManager.MATCH_INSTANT;
4793        } else {
4794            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4795            final boolean allowMatchInstant = wantInstantApps
4796                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4797            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4798                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4799            if (!allowMatchInstant) {
4800                flags &= ~PackageManager.MATCH_INSTANT;
4801            }
4802        }
4803        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4804    }
4805
4806    @Override
4807    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4808        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4809    }
4810
4811    /**
4812     * Important: The provided filterCallingUid is used exclusively to filter out activities
4813     * that can be seen based on user state. It's typically the original caller uid prior
4814     * to clearing. Because it can only be provided by trusted code, it's value can be
4815     * trusted and will be used as-is; unlike userId which will be validated by this method.
4816     */
4817    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4818            int filterCallingUid, int userId) {
4819        if (!sUserManager.exists(userId)) return null;
4820        flags = updateFlagsForComponent(flags, userId, component);
4821
4822        if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) {
4823            mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4824                    false /* requireFullPermission */, false /* checkShell */, "get activity info");
4825        }
4826
4827        synchronized (mPackages) {
4828            PackageParser.Activity a = mActivities.mActivities.get(component);
4829
4830            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4831            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4832                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4833                if (ps == null) return null;
4834                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4835                    return null;
4836                }
4837                return PackageParser.generateActivityInfo(
4838                        a, flags, ps.readUserState(userId), userId);
4839            }
4840            if (mResolveComponentName.equals(component)) {
4841                return PackageParser.generateActivityInfo(
4842                        mResolveActivity, flags, new PackageUserState(), userId);
4843            }
4844        }
4845        return null;
4846    }
4847
4848    private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) {
4849        if (!getActivityManagerInternal().isCallerRecents(callingUid)) {
4850            return false;
4851        }
4852        final long token = Binder.clearCallingIdentity();
4853        try {
4854            final int callingUserId = UserHandle.getUserId(callingUid);
4855            if (ActivityManager.getCurrentUser() != callingUserId) {
4856                return false;
4857            }
4858            return sUserManager.isSameProfileGroup(callingUserId, targetUserId);
4859        } finally {
4860            Binder.restoreCallingIdentity(token);
4861        }
4862    }
4863
4864    @Override
4865    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4866            String resolvedType) {
4867        synchronized (mPackages) {
4868            if (component.equals(mResolveComponentName)) {
4869                // The resolver supports EVERYTHING!
4870                return true;
4871            }
4872            final int callingUid = Binder.getCallingUid();
4873            final int callingUserId = UserHandle.getUserId(callingUid);
4874            PackageParser.Activity a = mActivities.mActivities.get(component);
4875            if (a == null) {
4876                return false;
4877            }
4878            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4879            if (ps == null) {
4880                return false;
4881            }
4882            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4883                return false;
4884            }
4885            for (int i=0; i<a.intents.size(); i++) {
4886                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4887                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4888                    return true;
4889                }
4890            }
4891            return false;
4892        }
4893    }
4894
4895    @Override
4896    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4897        if (!sUserManager.exists(userId)) return null;
4898        final int callingUid = Binder.getCallingUid();
4899        flags = updateFlagsForComponent(flags, userId, component);
4900        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4901                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4902        synchronized (mPackages) {
4903            PackageParser.Activity a = mReceivers.mActivities.get(component);
4904            if (DEBUG_PACKAGE_INFO) Log.v(
4905                TAG, "getReceiverInfo " + component + ": " + a);
4906            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4907                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4908                if (ps == null) return null;
4909                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4910                    return null;
4911                }
4912                return PackageParser.generateActivityInfo(
4913                        a, flags, ps.readUserState(userId), userId);
4914            }
4915        }
4916        return null;
4917    }
4918
4919    @Override
4920    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4921            int flags, int userId) {
4922        if (!sUserManager.exists(userId)) return null;
4923        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4924        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4925            return null;
4926        }
4927
4928        flags = updateFlagsForPackage(flags, userId, null);
4929
4930        final boolean canSeeStaticLibraries =
4931                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4932                        == PERMISSION_GRANTED
4933                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4934                        == PERMISSION_GRANTED
4935                || canRequestPackageInstallsInternal(packageName,
4936                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4937                        false  /* throwIfPermNotDeclared*/)
4938                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4939                        == PERMISSION_GRANTED;
4940
4941        synchronized (mPackages) {
4942            List<SharedLibraryInfo> result = null;
4943
4944            final int libCount = mSharedLibraries.size();
4945            for (int i = 0; i < libCount; i++) {
4946                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4947                if (versionedLib == null) {
4948                    continue;
4949                }
4950
4951                final int versionCount = versionedLib.size();
4952                for (int j = 0; j < versionCount; j++) {
4953                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4954                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4955                        break;
4956                    }
4957                    final long identity = Binder.clearCallingIdentity();
4958                    try {
4959                        PackageInfo packageInfo = getPackageInfoVersioned(
4960                                libInfo.getDeclaringPackage(), flags
4961                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4962                        if (packageInfo == null) {
4963                            continue;
4964                        }
4965                    } finally {
4966                        Binder.restoreCallingIdentity(identity);
4967                    }
4968
4969                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4970                            libInfo.getLongVersion(), libInfo.getType(),
4971                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4972                            flags, userId));
4973
4974                    if (result == null) {
4975                        result = new ArrayList<>();
4976                    }
4977                    result.add(resLibInfo);
4978                }
4979            }
4980
4981            return result != null ? new ParceledListSlice<>(result) : null;
4982        }
4983    }
4984
4985    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4986            SharedLibraryInfo libInfo, int flags, int userId) {
4987        List<VersionedPackage> versionedPackages = null;
4988        final int packageCount = mSettings.mPackages.size();
4989        for (int i = 0; i < packageCount; i++) {
4990            PackageSetting ps = mSettings.mPackages.valueAt(i);
4991
4992            if (ps == null) {
4993                continue;
4994            }
4995
4996            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4997                continue;
4998            }
4999
5000            final String libName = libInfo.getName();
5001            if (libInfo.isStatic()) {
5002                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5003                if (libIdx < 0) {
5004                    continue;
5005                }
5006                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
5007                    continue;
5008                }
5009                if (versionedPackages == null) {
5010                    versionedPackages = new ArrayList<>();
5011                }
5012                // If the dependent is a static shared lib, use the public package name
5013                String dependentPackageName = ps.name;
5014                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5015                    dependentPackageName = ps.pkg.manifestPackageName;
5016                }
5017                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5018            } else if (ps.pkg != null) {
5019                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5020                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5021                    if (versionedPackages == null) {
5022                        versionedPackages = new ArrayList<>();
5023                    }
5024                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5025                }
5026            }
5027        }
5028
5029        return versionedPackages;
5030    }
5031
5032    @Override
5033    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5034        if (!sUserManager.exists(userId)) return null;
5035        final int callingUid = Binder.getCallingUid();
5036        flags = updateFlagsForComponent(flags, userId, component);
5037        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5038                false /* requireFullPermission */, false /* checkShell */, "get service info");
5039        synchronized (mPackages) {
5040            PackageParser.Service s = mServices.mServices.get(component);
5041            if (DEBUG_PACKAGE_INFO) Log.v(
5042                TAG, "getServiceInfo " + component + ": " + s);
5043            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5044                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5045                if (ps == null) return null;
5046                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5047                    return null;
5048                }
5049                return PackageParser.generateServiceInfo(
5050                        s, flags, ps.readUserState(userId), userId);
5051            }
5052        }
5053        return null;
5054    }
5055
5056    @Override
5057    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5058        if (!sUserManager.exists(userId)) return null;
5059        final int callingUid = Binder.getCallingUid();
5060        flags = updateFlagsForComponent(flags, userId, component);
5061        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5062                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5063        synchronized (mPackages) {
5064            PackageParser.Provider p = mProviders.mProviders.get(component);
5065            if (DEBUG_PACKAGE_INFO) Log.v(
5066                TAG, "getProviderInfo " + component + ": " + p);
5067            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5068                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5069                if (ps == null) return null;
5070                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5071                    return null;
5072                }
5073                return PackageParser.generateProviderInfo(
5074                        p, flags, ps.readUserState(userId), userId);
5075            }
5076        }
5077        return null;
5078    }
5079
5080    @Override
5081    public String[] getSystemSharedLibraryNames() {
5082        // allow instant applications
5083        synchronized (mPackages) {
5084            Set<String> libs = null;
5085            final int libCount = mSharedLibraries.size();
5086            for (int i = 0; i < libCount; i++) {
5087                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5088                if (versionedLib == null) {
5089                    continue;
5090                }
5091                final int versionCount = versionedLib.size();
5092                for (int j = 0; j < versionCount; j++) {
5093                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5094                    if (!libEntry.info.isStatic()) {
5095                        if (libs == null) {
5096                            libs = new ArraySet<>();
5097                        }
5098                        libs.add(libEntry.info.getName());
5099                        break;
5100                    }
5101                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5102                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5103                            UserHandle.getUserId(Binder.getCallingUid()),
5104                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5105                        if (libs == null) {
5106                            libs = new ArraySet<>();
5107                        }
5108                        libs.add(libEntry.info.getName());
5109                        break;
5110                    }
5111                }
5112            }
5113
5114            if (libs != null) {
5115                String[] libsArray = new String[libs.size()];
5116                libs.toArray(libsArray);
5117                return libsArray;
5118            }
5119
5120            return null;
5121        }
5122    }
5123
5124    @Override
5125    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5126        // allow instant applications
5127        synchronized (mPackages) {
5128            return mServicesSystemSharedLibraryPackageName;
5129        }
5130    }
5131
5132    @Override
5133    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5134        // allow instant applications
5135        synchronized (mPackages) {
5136            return mSharedSystemSharedLibraryPackageName;
5137        }
5138    }
5139
5140    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5141        for (int i = userList.length - 1; i >= 0; --i) {
5142            final int userId = userList[i];
5143            // don't add instant app to the list of updates
5144            if (pkgSetting.getInstantApp(userId)) {
5145                continue;
5146            }
5147            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5148            if (changedPackages == null) {
5149                changedPackages = new SparseArray<>();
5150                mChangedPackages.put(userId, changedPackages);
5151            }
5152            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5153            if (sequenceNumbers == null) {
5154                sequenceNumbers = new HashMap<>();
5155                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5156            }
5157            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5158            if (sequenceNumber != null) {
5159                changedPackages.remove(sequenceNumber);
5160            }
5161            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5162            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5163        }
5164        mChangedPackagesSequenceNumber++;
5165    }
5166
5167    @Override
5168    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5169        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5170            return null;
5171        }
5172        synchronized (mPackages) {
5173            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5174                return null;
5175            }
5176            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5177            if (changedPackages == null) {
5178                return null;
5179            }
5180            final List<String> packageNames =
5181                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5182            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5183                final String packageName = changedPackages.get(i);
5184                if (packageName != null) {
5185                    packageNames.add(packageName);
5186                }
5187            }
5188            return packageNames.isEmpty()
5189                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5190        }
5191    }
5192
5193    @Override
5194    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5195        // allow instant applications
5196        ArrayList<FeatureInfo> res;
5197        synchronized (mAvailableFeatures) {
5198            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5199            res.addAll(mAvailableFeatures.values());
5200        }
5201        final FeatureInfo fi = new FeatureInfo();
5202        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5203                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5204        res.add(fi);
5205
5206        return new ParceledListSlice<>(res);
5207    }
5208
5209    @Override
5210    public boolean hasSystemFeature(String name, int version) {
5211        // allow instant applications
5212        synchronized (mAvailableFeatures) {
5213            final FeatureInfo feat = mAvailableFeatures.get(name);
5214            if (feat == null) {
5215                return false;
5216            } else {
5217                return feat.version >= version;
5218            }
5219        }
5220    }
5221
5222    @Override
5223    public int checkPermission(String permName, String pkgName, int userId) {
5224        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5225    }
5226
5227    @Override
5228    public int checkUidPermission(String permName, int uid) {
5229        synchronized (mPackages) {
5230            final String[] packageNames = getPackagesForUid(uid);
5231            final PackageParser.Package pkg = (packageNames != null && packageNames.length > 0)
5232                    ? mPackages.get(packageNames[0])
5233                    : null;
5234            return mPermissionManager.checkUidPermission(permName, pkg, uid, getCallingUid());
5235        }
5236    }
5237
5238    @Override
5239    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5240        if (UserHandle.getCallingUserId() != userId) {
5241            mContext.enforceCallingPermission(
5242                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5243                    "isPermissionRevokedByPolicy for user " + userId);
5244        }
5245
5246        if (checkPermission(permission, packageName, userId)
5247                == PackageManager.PERMISSION_GRANTED) {
5248            return false;
5249        }
5250
5251        final int callingUid = Binder.getCallingUid();
5252        if (getInstantAppPackageName(callingUid) != null) {
5253            if (!isCallerSameApp(packageName, callingUid)) {
5254                return false;
5255            }
5256        } else {
5257            if (isInstantApp(packageName, userId)) {
5258                return false;
5259            }
5260        }
5261
5262        final long identity = Binder.clearCallingIdentity();
5263        try {
5264            final int flags = getPermissionFlags(permission, packageName, userId);
5265            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5266        } finally {
5267            Binder.restoreCallingIdentity(identity);
5268        }
5269    }
5270
5271    @Override
5272    public String getPermissionControllerPackageName() {
5273        synchronized (mPackages) {
5274            return mRequiredInstallerPackage;
5275        }
5276    }
5277
5278    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5279        return mPermissionManager.addDynamicPermission(
5280                info, async, getCallingUid(), new PermissionCallback() {
5281                    @Override
5282                    public void onPermissionChanged() {
5283                        if (!async) {
5284                            mSettings.writeLPr();
5285                        } else {
5286                            scheduleWriteSettingsLocked();
5287                        }
5288                    }
5289                });
5290    }
5291
5292    @Override
5293    public boolean addPermission(PermissionInfo info) {
5294        synchronized (mPackages) {
5295            return addDynamicPermission(info, false);
5296        }
5297    }
5298
5299    @Override
5300    public boolean addPermissionAsync(PermissionInfo info) {
5301        synchronized (mPackages) {
5302            return addDynamicPermission(info, true);
5303        }
5304    }
5305
5306    @Override
5307    public void removePermission(String permName) {
5308        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5309    }
5310
5311    @Override
5312    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5313        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5314                getCallingUid(), userId, mPermissionCallback);
5315    }
5316
5317    @Override
5318    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5319        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5320                getCallingUid(), userId, mPermissionCallback);
5321    }
5322
5323    @Override
5324    public void resetRuntimePermissions() {
5325        mContext.enforceCallingOrSelfPermission(
5326                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5327                "revokeRuntimePermission");
5328
5329        int callingUid = Binder.getCallingUid();
5330        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5331            mContext.enforceCallingOrSelfPermission(
5332                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5333                    "resetRuntimePermissions");
5334        }
5335
5336        synchronized (mPackages) {
5337            mPermissionManager.updateAllPermissions(
5338                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5339                    mPermissionCallback);
5340            for (int userId : UserManagerService.getInstance().getUserIds()) {
5341                final int packageCount = mPackages.size();
5342                for (int i = 0; i < packageCount; i++) {
5343                    PackageParser.Package pkg = mPackages.valueAt(i);
5344                    if (!(pkg.mExtras instanceof PackageSetting)) {
5345                        continue;
5346                    }
5347                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5348                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5349                }
5350            }
5351        }
5352    }
5353
5354    @Override
5355    public int getPermissionFlags(String permName, String packageName, int userId) {
5356        return mPermissionManager.getPermissionFlags(
5357                permName, packageName, getCallingUid(), userId);
5358    }
5359
5360    @Override
5361    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5362            int flagValues, int userId) {
5363        mPermissionManager.updatePermissionFlags(
5364                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5365                mPermissionCallback);
5366    }
5367
5368    /**
5369     * Update the permission flags for all packages and runtime permissions of a user in order
5370     * to allow device or profile owner to remove POLICY_FIXED.
5371     */
5372    @Override
5373    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5374        synchronized (mPackages) {
5375            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5376                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5377                    mPermissionCallback);
5378            if (changed) {
5379                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5380            }
5381        }
5382    }
5383
5384    @Override
5385    public boolean shouldShowRequestPermissionRationale(String permissionName,
5386            String packageName, int userId) {
5387        if (UserHandle.getCallingUserId() != userId) {
5388            mContext.enforceCallingPermission(
5389                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5390                    "canShowRequestPermissionRationale for user " + userId);
5391        }
5392
5393        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5394        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5395            return false;
5396        }
5397
5398        if (checkPermission(permissionName, packageName, userId)
5399                == PackageManager.PERMISSION_GRANTED) {
5400            return false;
5401        }
5402
5403        final int flags;
5404
5405        final long identity = Binder.clearCallingIdentity();
5406        try {
5407            flags = getPermissionFlags(permissionName,
5408                    packageName, userId);
5409        } finally {
5410            Binder.restoreCallingIdentity(identity);
5411        }
5412
5413        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5414                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5415                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5416
5417        if ((flags & fixedFlags) != 0) {
5418            return false;
5419        }
5420
5421        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5422    }
5423
5424    @Override
5425    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5426        mContext.enforceCallingOrSelfPermission(
5427                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5428                "addOnPermissionsChangeListener");
5429
5430        synchronized (mPackages) {
5431            mOnPermissionChangeListeners.addListenerLocked(listener);
5432        }
5433    }
5434
5435    @Override
5436    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5437        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5438            throw new SecurityException("Instant applications don't have access to this method");
5439        }
5440        synchronized (mPackages) {
5441            mOnPermissionChangeListeners.removeListenerLocked(listener);
5442        }
5443    }
5444
5445    @Override
5446    public boolean isProtectedBroadcast(String actionName) {
5447        // allow instant applications
5448        synchronized (mProtectedBroadcasts) {
5449            if (mProtectedBroadcasts.contains(actionName)) {
5450                return true;
5451            } else if (actionName != null) {
5452                // TODO: remove these terrible hacks
5453                if (actionName.startsWith("android.net.netmon.lingerExpired")
5454                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5455                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5456                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5457                    return true;
5458                }
5459            }
5460        }
5461        return false;
5462    }
5463
5464    @Override
5465    public int checkSignatures(String pkg1, String pkg2) {
5466        synchronized (mPackages) {
5467            final PackageParser.Package p1 = mPackages.get(pkg1);
5468            final PackageParser.Package p2 = mPackages.get(pkg2);
5469            if (p1 == null || p1.mExtras == null
5470                    || p2 == null || p2.mExtras == null) {
5471                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5472            }
5473            final int callingUid = Binder.getCallingUid();
5474            final int callingUserId = UserHandle.getUserId(callingUid);
5475            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5476            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5477            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5478                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5479                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5480            }
5481            return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures);
5482        }
5483    }
5484
5485    @Override
5486    public int checkUidSignatures(int uid1, int uid2) {
5487        final int callingUid = Binder.getCallingUid();
5488        final int callingUserId = UserHandle.getUserId(callingUid);
5489        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5490        // Map to base uids.
5491        uid1 = UserHandle.getAppId(uid1);
5492        uid2 = UserHandle.getAppId(uid2);
5493        // reader
5494        synchronized (mPackages) {
5495            Signature[] s1;
5496            Signature[] s2;
5497            Object obj = mSettings.getUserIdLPr(uid1);
5498            if (obj != null) {
5499                if (obj instanceof SharedUserSetting) {
5500                    if (isCallerInstantApp) {
5501                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5502                    }
5503                    s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5504                } else if (obj instanceof PackageSetting) {
5505                    final PackageSetting ps = (PackageSetting) obj;
5506                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5507                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5508                    }
5509                    s1 = ps.signatures.mSigningDetails.signatures;
5510                } else {
5511                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5512                }
5513            } else {
5514                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5515            }
5516            obj = mSettings.getUserIdLPr(uid2);
5517            if (obj != null) {
5518                if (obj instanceof SharedUserSetting) {
5519                    if (isCallerInstantApp) {
5520                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5521                    }
5522                    s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5523                } else if (obj instanceof PackageSetting) {
5524                    final PackageSetting ps = (PackageSetting) obj;
5525                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5526                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5527                    }
5528                    s2 = ps.signatures.mSigningDetails.signatures;
5529                } else {
5530                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5531                }
5532            } else {
5533                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5534            }
5535            return compareSignatures(s1, s2);
5536        }
5537    }
5538
5539    @Override
5540    public boolean hasSigningCertificate(
5541            String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) {
5542
5543        synchronized (mPackages) {
5544            final PackageParser.Package p = mPackages.get(packageName);
5545            if (p == null || p.mExtras == null) {
5546                return false;
5547            }
5548            final int callingUid = Binder.getCallingUid();
5549            final int callingUserId = UserHandle.getUserId(callingUid);
5550            final PackageSetting ps = (PackageSetting) p.mExtras;
5551            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5552                return false;
5553            }
5554            switch (type) {
5555                case CERT_INPUT_RAW_X509:
5556                    return p.mSigningDetails.hasCertificate(certificate);
5557                case CERT_INPUT_SHA256:
5558                    return p.mSigningDetails.hasSha256Certificate(certificate);
5559                default:
5560                    return false;
5561            }
5562        }
5563    }
5564
5565    @Override
5566    public boolean hasUidSigningCertificate(
5567            int uid, byte[] certificate, @PackageManager.CertificateInputType int type) {
5568        final int callingUid = Binder.getCallingUid();
5569        final int callingUserId = UserHandle.getUserId(callingUid);
5570        // Map to base uids.
5571        uid = UserHandle.getAppId(uid);
5572        // reader
5573        synchronized (mPackages) {
5574            final PackageParser.SigningDetails signingDetails;
5575            final Object obj = mSettings.getUserIdLPr(uid);
5576            if (obj != null) {
5577                if (obj instanceof SharedUserSetting) {
5578                    final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5579                    if (isCallerInstantApp) {
5580                        return false;
5581                    }
5582                    signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails;
5583                } else if (obj instanceof PackageSetting) {
5584                    final PackageSetting ps = (PackageSetting) obj;
5585                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5586                        return false;
5587                    }
5588                    signingDetails = ps.signatures.mSigningDetails;
5589                } else {
5590                    return false;
5591                }
5592            } else {
5593                return false;
5594            }
5595            switch (type) {
5596                case CERT_INPUT_RAW_X509:
5597                    return signingDetails.hasCertificate(certificate);
5598                case CERT_INPUT_SHA256:
5599                    return signingDetails.hasSha256Certificate(certificate);
5600                default:
5601                    return false;
5602            }
5603        }
5604    }
5605
5606    /**
5607     * This method should typically only be used when granting or revoking
5608     * permissions, since the app may immediately restart after this call.
5609     * <p>
5610     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5611     * guard your work against the app being relaunched.
5612     */
5613    private void killUid(int appId, int userId, String reason) {
5614        final long identity = Binder.clearCallingIdentity();
5615        try {
5616            IActivityManager am = ActivityManager.getService();
5617            if (am != null) {
5618                try {
5619                    am.killUid(appId, userId, reason);
5620                } catch (RemoteException e) {
5621                    /* ignore - same process */
5622                }
5623            }
5624        } finally {
5625            Binder.restoreCallingIdentity(identity);
5626        }
5627    }
5628
5629    /**
5630     * If the database version for this type of package (internal storage or
5631     * external storage) is less than the version where package signatures
5632     * were updated, return true.
5633     */
5634    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5635        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5636        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5637    }
5638
5639    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5640        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5641        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5642    }
5643
5644    @Override
5645    public List<String> getAllPackages() {
5646        final int callingUid = Binder.getCallingUid();
5647        final int callingUserId = UserHandle.getUserId(callingUid);
5648        synchronized (mPackages) {
5649            if (canViewInstantApps(callingUid, callingUserId)) {
5650                return new ArrayList<String>(mPackages.keySet());
5651            }
5652            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5653            final List<String> result = new ArrayList<>();
5654            if (instantAppPkgName != null) {
5655                // caller is an instant application; filter unexposed applications
5656                for (PackageParser.Package pkg : mPackages.values()) {
5657                    if (!pkg.visibleToInstantApps) {
5658                        continue;
5659                    }
5660                    result.add(pkg.packageName);
5661                }
5662            } else {
5663                // caller is a normal application; filter instant applications
5664                for (PackageParser.Package pkg : mPackages.values()) {
5665                    final PackageSetting ps =
5666                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5667                    if (ps != null
5668                            && ps.getInstantApp(callingUserId)
5669                            && !mInstantAppRegistry.isInstantAccessGranted(
5670                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5671                        continue;
5672                    }
5673                    result.add(pkg.packageName);
5674                }
5675            }
5676            return result;
5677        }
5678    }
5679
5680    @Override
5681    public String[] getPackagesForUid(int uid) {
5682        final int callingUid = Binder.getCallingUid();
5683        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5684        final int userId = UserHandle.getUserId(uid);
5685        uid = UserHandle.getAppId(uid);
5686        // reader
5687        synchronized (mPackages) {
5688            Object obj = mSettings.getUserIdLPr(uid);
5689            if (obj instanceof SharedUserSetting) {
5690                if (isCallerInstantApp) {
5691                    return null;
5692                }
5693                final SharedUserSetting sus = (SharedUserSetting) obj;
5694                final int N = sus.packages.size();
5695                String[] res = new String[N];
5696                final Iterator<PackageSetting> it = sus.packages.iterator();
5697                int i = 0;
5698                while (it.hasNext()) {
5699                    PackageSetting ps = it.next();
5700                    if (ps.getInstalled(userId)) {
5701                        res[i++] = ps.name;
5702                    } else {
5703                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5704                    }
5705                }
5706                return res;
5707            } else if (obj instanceof PackageSetting) {
5708                final PackageSetting ps = (PackageSetting) obj;
5709                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5710                    return new String[]{ps.name};
5711                }
5712            }
5713        }
5714        return null;
5715    }
5716
5717    @Override
5718    public String getNameForUid(int uid) {
5719        final int callingUid = Binder.getCallingUid();
5720        if (getInstantAppPackageName(callingUid) != null) {
5721            return null;
5722        }
5723        synchronized (mPackages) {
5724            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5725            if (obj instanceof SharedUserSetting) {
5726                final SharedUserSetting sus = (SharedUserSetting) obj;
5727                return sus.name + ":" + sus.userId;
5728            } else if (obj instanceof PackageSetting) {
5729                final PackageSetting ps = (PackageSetting) obj;
5730                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5731                    return null;
5732                }
5733                return ps.name;
5734            }
5735            return null;
5736        }
5737    }
5738
5739    @Override
5740    public String[] getNamesForUids(int[] uids) {
5741        if (uids == null || uids.length == 0) {
5742            return null;
5743        }
5744        final int callingUid = Binder.getCallingUid();
5745        if (getInstantAppPackageName(callingUid) != null) {
5746            return null;
5747        }
5748        final String[] names = new String[uids.length];
5749        synchronized (mPackages) {
5750            for (int i = uids.length - 1; i >= 0; i--) {
5751                final int uid = uids[i];
5752                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5753                if (obj instanceof SharedUserSetting) {
5754                    final SharedUserSetting sus = (SharedUserSetting) obj;
5755                    names[i] = "shared:" + sus.name;
5756                } else if (obj instanceof PackageSetting) {
5757                    final PackageSetting ps = (PackageSetting) obj;
5758                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5759                        names[i] = null;
5760                    } else {
5761                        names[i] = ps.name;
5762                    }
5763                } else {
5764                    names[i] = null;
5765                }
5766            }
5767        }
5768        return names;
5769    }
5770
5771    @Override
5772    public int getUidForSharedUser(String sharedUserName) {
5773        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5774            return -1;
5775        }
5776        if (sharedUserName == null) {
5777            return -1;
5778        }
5779        // reader
5780        synchronized (mPackages) {
5781            SharedUserSetting suid;
5782            try {
5783                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5784                if (suid != null) {
5785                    return suid.userId;
5786                }
5787            } catch (PackageManagerException ignore) {
5788                // can't happen, but, still need to catch it
5789            }
5790            return -1;
5791        }
5792    }
5793
5794    @Override
5795    public int getFlagsForUid(int uid) {
5796        final int callingUid = Binder.getCallingUid();
5797        if (getInstantAppPackageName(callingUid) != null) {
5798            return 0;
5799        }
5800        synchronized (mPackages) {
5801            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5802            if (obj instanceof SharedUserSetting) {
5803                final SharedUserSetting sus = (SharedUserSetting) obj;
5804                return sus.pkgFlags;
5805            } else if (obj instanceof PackageSetting) {
5806                final PackageSetting ps = (PackageSetting) obj;
5807                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5808                    return 0;
5809                }
5810                return ps.pkgFlags;
5811            }
5812        }
5813        return 0;
5814    }
5815
5816    @Override
5817    public int getPrivateFlagsForUid(int uid) {
5818        final int callingUid = Binder.getCallingUid();
5819        if (getInstantAppPackageName(callingUid) != null) {
5820            return 0;
5821        }
5822        synchronized (mPackages) {
5823            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5824            if (obj instanceof SharedUserSetting) {
5825                final SharedUserSetting sus = (SharedUserSetting) obj;
5826                return sus.pkgPrivateFlags;
5827            } else if (obj instanceof PackageSetting) {
5828                final PackageSetting ps = (PackageSetting) obj;
5829                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5830                    return 0;
5831                }
5832                return ps.pkgPrivateFlags;
5833            }
5834        }
5835        return 0;
5836    }
5837
5838    @Override
5839    public boolean isUidPrivileged(int uid) {
5840        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5841            return false;
5842        }
5843        uid = UserHandle.getAppId(uid);
5844        // reader
5845        synchronized (mPackages) {
5846            Object obj = mSettings.getUserIdLPr(uid);
5847            if (obj instanceof SharedUserSetting) {
5848                final SharedUserSetting sus = (SharedUserSetting) obj;
5849                final Iterator<PackageSetting> it = sus.packages.iterator();
5850                while (it.hasNext()) {
5851                    if (it.next().isPrivileged()) {
5852                        return true;
5853                    }
5854                }
5855            } else if (obj instanceof PackageSetting) {
5856                final PackageSetting ps = (PackageSetting) obj;
5857                return ps.isPrivileged();
5858            }
5859        }
5860        return false;
5861    }
5862
5863    @Override
5864    public String[] getAppOpPermissionPackages(String permName) {
5865        return mPermissionManager.getAppOpPermissionPackages(permName);
5866    }
5867
5868    @Override
5869    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5870            int flags, int userId) {
5871        return resolveIntentInternal(
5872                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5873    }
5874
5875    /**
5876     * Normally instant apps can only be resolved when they're visible to the caller.
5877     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5878     * since we need to allow the system to start any installed application.
5879     */
5880    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5881            int flags, int userId, boolean resolveForStart) {
5882        try {
5883            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5884
5885            if (!sUserManager.exists(userId)) return null;
5886            final int callingUid = Binder.getCallingUid();
5887            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5888            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5889                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5890
5891            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5892            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5893                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5894            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5895
5896            final ResolveInfo bestChoice =
5897                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5898            return bestChoice;
5899        } finally {
5900            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5901        }
5902    }
5903
5904    @Override
5905    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5906        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5907            throw new SecurityException(
5908                    "findPersistentPreferredActivity can only be run by the system");
5909        }
5910        if (!sUserManager.exists(userId)) {
5911            return null;
5912        }
5913        final int callingUid = Binder.getCallingUid();
5914        intent = updateIntentForResolve(intent);
5915        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5916        final int flags = updateFlagsForResolve(
5917                0, userId, intent, callingUid, false /*includeInstantApps*/);
5918        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5919                userId);
5920        synchronized (mPackages) {
5921            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5922                    userId);
5923        }
5924    }
5925
5926    @Override
5927    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5928            IntentFilter filter, int match, ComponentName activity) {
5929        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5930            return;
5931        }
5932        final int userId = UserHandle.getCallingUserId();
5933        if (DEBUG_PREFERRED) {
5934            Log.v(TAG, "setLastChosenActivity intent=" + intent
5935                + " resolvedType=" + resolvedType
5936                + " flags=" + flags
5937                + " filter=" + filter
5938                + " match=" + match
5939                + " activity=" + activity);
5940            filter.dump(new PrintStreamPrinter(System.out), "    ");
5941        }
5942        intent.setComponent(null);
5943        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5944                userId);
5945        // Find any earlier preferred or last chosen entries and nuke them
5946        findPreferredActivity(intent, resolvedType,
5947                flags, query, 0, false, true, false, userId);
5948        // Add the new activity as the last chosen for this filter
5949        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5950                "Setting last chosen");
5951    }
5952
5953    @Override
5954    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5955        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5956            return null;
5957        }
5958        final int userId = UserHandle.getCallingUserId();
5959        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5960        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5961                userId);
5962        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5963                false, false, false, userId);
5964    }
5965
5966    /**
5967     * Returns whether or not instant apps have been disabled remotely.
5968     */
5969    private boolean areWebInstantAppsDisabled() {
5970        return mWebInstantAppsDisabled;
5971    }
5972
5973    private boolean isInstantAppResolutionAllowed(
5974            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5975            boolean skipPackageCheck) {
5976        if (mInstantAppResolverConnection == null) {
5977            return false;
5978        }
5979        if (mInstantAppInstallerActivity == null) {
5980            return false;
5981        }
5982        if (intent.getComponent() != null) {
5983            return false;
5984        }
5985        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5986            return false;
5987        }
5988        if (!skipPackageCheck && intent.getPackage() != null) {
5989            return false;
5990        }
5991        if (!intent.isWebIntent()) {
5992            // for non web intents, we should not resolve externally if an app already exists to
5993            // handle it or if the caller didn't explicitly request it.
5994            if ((resolvedActivities != null && resolvedActivities.size() != 0)
5995                    || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) {
5996                return false;
5997            }
5998        } else {
5999            if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) {
6000                return false;
6001            } else if (areWebInstantAppsDisabled()) {
6002                return false;
6003            }
6004        }
6005        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6006        // Or if there's already an ephemeral app installed that handles the action
6007        synchronized (mPackages) {
6008            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6009            for (int n = 0; n < count; n++) {
6010                final ResolveInfo info = resolvedActivities.get(n);
6011                final String packageName = info.activityInfo.packageName;
6012                final PackageSetting ps = mSettings.mPackages.get(packageName);
6013                if (ps != null) {
6014                    // only check domain verification status if the app is not a browser
6015                    if (!info.handleAllWebDataURI) {
6016                        // Try to get the status from User settings first
6017                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6018                        final int status = (int) (packedStatus >> 32);
6019                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6020                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6021                            if (DEBUG_INSTANT) {
6022                                Slog.v(TAG, "DENY instant app;"
6023                                    + " pkg: " + packageName + ", status: " + status);
6024                            }
6025                            return false;
6026                        }
6027                    }
6028                    if (ps.getInstantApp(userId)) {
6029                        if (DEBUG_INSTANT) {
6030                            Slog.v(TAG, "DENY instant app installed;"
6031                                    + " pkg: " + packageName);
6032                        }
6033                        return false;
6034                    }
6035                }
6036            }
6037        }
6038        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6039        return true;
6040    }
6041
6042    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6043            Intent origIntent, String resolvedType, String callingPackage,
6044            Bundle verificationBundle, int userId) {
6045        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6046                new InstantAppRequest(responseObj, origIntent, resolvedType,
6047                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6048        mHandler.sendMessage(msg);
6049    }
6050
6051    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6052            int flags, List<ResolveInfo> query, int userId) {
6053        if (query != null) {
6054            final int N = query.size();
6055            if (N == 1) {
6056                return query.get(0);
6057            } else if (N > 1) {
6058                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6059                // If there is more than one activity with the same priority,
6060                // then let the user decide between them.
6061                ResolveInfo r0 = query.get(0);
6062                ResolveInfo r1 = query.get(1);
6063                if (DEBUG_INTENT_MATCHING || debug) {
6064                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6065                            + r1.activityInfo.name + "=" + r1.priority);
6066                }
6067                // If the first activity has a higher priority, or a different
6068                // default, then it is always desirable to pick it.
6069                if (r0.priority != r1.priority
6070                        || r0.preferredOrder != r1.preferredOrder
6071                        || r0.isDefault != r1.isDefault) {
6072                    return query.get(0);
6073                }
6074                // If we have saved a preference for a preferred activity for
6075                // this Intent, use that.
6076                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6077                        flags, query, r0.priority, true, false, debug, userId);
6078                if (ri != null) {
6079                    return ri;
6080                }
6081                // If we have an ephemeral app, use it
6082                for (int i = 0; i < N; i++) {
6083                    ri = query.get(i);
6084                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6085                        final String packageName = ri.activityInfo.packageName;
6086                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6087                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6088                        final int status = (int)(packedStatus >> 32);
6089                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6090                            return ri;
6091                        }
6092                    }
6093                }
6094                ri = new ResolveInfo(mResolveInfo);
6095                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6096                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6097                // If all of the options come from the same package, show the application's
6098                // label and icon instead of the generic resolver's.
6099                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6100                // and then throw away the ResolveInfo itself, meaning that the caller loses
6101                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6102                // a fallback for this case; we only set the target package's resources on
6103                // the ResolveInfo, not the ActivityInfo.
6104                final String intentPackage = intent.getPackage();
6105                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6106                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6107                    ri.resolvePackageName = intentPackage;
6108                    if (userNeedsBadging(userId)) {
6109                        ri.noResourceId = true;
6110                    } else {
6111                        ri.icon = appi.icon;
6112                    }
6113                    ri.iconResourceId = appi.icon;
6114                    ri.labelRes = appi.labelRes;
6115                }
6116                ri.activityInfo.applicationInfo = new ApplicationInfo(
6117                        ri.activityInfo.applicationInfo);
6118                if (userId != 0) {
6119                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6120                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6121                }
6122                // Make sure that the resolver is displayable in car mode
6123                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6124                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6125                return ri;
6126            }
6127        }
6128        return null;
6129    }
6130
6131    /**
6132     * Return true if the given list is not empty and all of its contents have
6133     * an activityInfo with the given package name.
6134     */
6135    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6136        if (ArrayUtils.isEmpty(list)) {
6137            return false;
6138        }
6139        for (int i = 0, N = list.size(); i < N; i++) {
6140            final ResolveInfo ri = list.get(i);
6141            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6142            if (ai == null || !packageName.equals(ai.packageName)) {
6143                return false;
6144            }
6145        }
6146        return true;
6147    }
6148
6149    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6150            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6151        final int N = query.size();
6152        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6153                .get(userId);
6154        // Get the list of persistent preferred activities that handle the intent
6155        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6156        List<PersistentPreferredActivity> pprefs = ppir != null
6157                ? ppir.queryIntent(intent, resolvedType,
6158                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6159                        userId)
6160                : null;
6161        if (pprefs != null && pprefs.size() > 0) {
6162            final int M = pprefs.size();
6163            for (int i=0; i<M; i++) {
6164                final PersistentPreferredActivity ppa = pprefs.get(i);
6165                if (DEBUG_PREFERRED || debug) {
6166                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6167                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6168                            + "\n  component=" + ppa.mComponent);
6169                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6170                }
6171                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6172                        flags | MATCH_DISABLED_COMPONENTS, userId);
6173                if (DEBUG_PREFERRED || debug) {
6174                    Slog.v(TAG, "Found persistent preferred activity:");
6175                    if (ai != null) {
6176                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6177                    } else {
6178                        Slog.v(TAG, "  null");
6179                    }
6180                }
6181                if (ai == null) {
6182                    // This previously registered persistent preferred activity
6183                    // component is no longer known. Ignore it and do NOT remove it.
6184                    continue;
6185                }
6186                for (int j=0; j<N; j++) {
6187                    final ResolveInfo ri = query.get(j);
6188                    if (!ri.activityInfo.applicationInfo.packageName
6189                            .equals(ai.applicationInfo.packageName)) {
6190                        continue;
6191                    }
6192                    if (!ri.activityInfo.name.equals(ai.name)) {
6193                        continue;
6194                    }
6195                    //  Found a persistent preference that can handle the intent.
6196                    if (DEBUG_PREFERRED || debug) {
6197                        Slog.v(TAG, "Returning persistent preferred activity: " +
6198                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6199                    }
6200                    return ri;
6201                }
6202            }
6203        }
6204        return null;
6205    }
6206
6207    // TODO: handle preferred activities missing while user has amnesia
6208    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6209            List<ResolveInfo> query, int priority, boolean always,
6210            boolean removeMatches, boolean debug, int userId) {
6211        if (!sUserManager.exists(userId)) return null;
6212        final int callingUid = Binder.getCallingUid();
6213        flags = updateFlagsForResolve(
6214                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6215        intent = updateIntentForResolve(intent);
6216        // writer
6217        synchronized (mPackages) {
6218            // Try to find a matching persistent preferred activity.
6219            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6220                    debug, userId);
6221
6222            // If a persistent preferred activity matched, use it.
6223            if (pri != null) {
6224                return pri;
6225            }
6226
6227            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6228            // Get the list of preferred activities that handle the intent
6229            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6230            List<PreferredActivity> prefs = pir != null
6231                    ? pir.queryIntent(intent, resolvedType,
6232                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6233                            userId)
6234                    : null;
6235            if (prefs != null && prefs.size() > 0) {
6236                boolean changed = false;
6237                try {
6238                    // First figure out how good the original match set is.
6239                    // We will only allow preferred activities that came
6240                    // from the same match quality.
6241                    int match = 0;
6242
6243                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6244
6245                    final int N = query.size();
6246                    for (int j=0; j<N; j++) {
6247                        final ResolveInfo ri = query.get(j);
6248                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6249                                + ": 0x" + Integer.toHexString(match));
6250                        if (ri.match > match) {
6251                            match = ri.match;
6252                        }
6253                    }
6254
6255                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6256                            + Integer.toHexString(match));
6257
6258                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6259                    final int M = prefs.size();
6260                    for (int i=0; i<M; i++) {
6261                        final PreferredActivity pa = prefs.get(i);
6262                        if (DEBUG_PREFERRED || debug) {
6263                            Slog.v(TAG, "Checking PreferredActivity ds="
6264                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6265                                    + "\n  component=" + pa.mPref.mComponent);
6266                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6267                        }
6268                        if (pa.mPref.mMatch != match) {
6269                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6270                                    + Integer.toHexString(pa.mPref.mMatch));
6271                            continue;
6272                        }
6273                        // If it's not an "always" type preferred activity and that's what we're
6274                        // looking for, skip it.
6275                        if (always && !pa.mPref.mAlways) {
6276                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6277                            continue;
6278                        }
6279                        final ActivityInfo ai = getActivityInfo(
6280                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6281                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6282                                userId);
6283                        if (DEBUG_PREFERRED || debug) {
6284                            Slog.v(TAG, "Found preferred activity:");
6285                            if (ai != null) {
6286                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6287                            } else {
6288                                Slog.v(TAG, "  null");
6289                            }
6290                        }
6291                        if (ai == null) {
6292                            // This previously registered preferred activity
6293                            // component is no longer known.  Most likely an update
6294                            // to the app was installed and in the new version this
6295                            // component no longer exists.  Clean it up by removing
6296                            // it from the preferred activities list, and skip it.
6297                            Slog.w(TAG, "Removing dangling preferred activity: "
6298                                    + pa.mPref.mComponent);
6299                            pir.removeFilter(pa);
6300                            changed = true;
6301                            continue;
6302                        }
6303                        for (int j=0; j<N; j++) {
6304                            final ResolveInfo ri = query.get(j);
6305                            if (!ri.activityInfo.applicationInfo.packageName
6306                                    .equals(ai.applicationInfo.packageName)) {
6307                                continue;
6308                            }
6309                            if (!ri.activityInfo.name.equals(ai.name)) {
6310                                continue;
6311                            }
6312
6313                            if (removeMatches) {
6314                                pir.removeFilter(pa);
6315                                changed = true;
6316                                if (DEBUG_PREFERRED) {
6317                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6318                                }
6319                                break;
6320                            }
6321
6322                            // Okay we found a previously set preferred or last chosen app.
6323                            // If the result set is different from when this
6324                            // was created, and is not a subset of the preferred set, we need to
6325                            // clear it and re-ask the user their preference, if we're looking for
6326                            // an "always" type entry.
6327                            if (always && !pa.mPref.sameSet(query)) {
6328                                if (pa.mPref.isSuperset(query)) {
6329                                    // some components of the set are no longer present in
6330                                    // the query, but the preferred activity can still be reused
6331                                    if (DEBUG_PREFERRED) {
6332                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6333                                                + " still valid as only non-preferred components"
6334                                                + " were removed for " + intent + " type "
6335                                                + resolvedType);
6336                                    }
6337                                    // remove obsolete components and re-add the up-to-date filter
6338                                    PreferredActivity freshPa = new PreferredActivity(pa,
6339                                            pa.mPref.mMatch,
6340                                            pa.mPref.discardObsoleteComponents(query),
6341                                            pa.mPref.mComponent,
6342                                            pa.mPref.mAlways);
6343                                    pir.removeFilter(pa);
6344                                    pir.addFilter(freshPa);
6345                                    changed = true;
6346                                } else {
6347                                    Slog.i(TAG,
6348                                            "Result set changed, dropping preferred activity for "
6349                                                    + intent + " type " + resolvedType);
6350                                    if (DEBUG_PREFERRED) {
6351                                        Slog.v(TAG, "Removing preferred activity since set changed "
6352                                                + pa.mPref.mComponent);
6353                                    }
6354                                    pir.removeFilter(pa);
6355                                    // Re-add the filter as a "last chosen" entry (!always)
6356                                    PreferredActivity lastChosen = new PreferredActivity(
6357                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6358                                    pir.addFilter(lastChosen);
6359                                    changed = true;
6360                                    return null;
6361                                }
6362                            }
6363
6364                            // Yay! Either the set matched or we're looking for the last chosen
6365                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6366                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6367                            return ri;
6368                        }
6369                    }
6370                } finally {
6371                    if (changed) {
6372                        if (DEBUG_PREFERRED) {
6373                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6374                        }
6375                        scheduleWritePackageRestrictionsLocked(userId);
6376                    }
6377                }
6378            }
6379        }
6380        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6381        return null;
6382    }
6383
6384    /*
6385     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6386     */
6387    @Override
6388    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6389            int targetUserId) {
6390        mContext.enforceCallingOrSelfPermission(
6391                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6392        List<CrossProfileIntentFilter> matches =
6393                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6394        if (matches != null) {
6395            int size = matches.size();
6396            for (int i = 0; i < size; i++) {
6397                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6398            }
6399        }
6400        if (intent.hasWebURI()) {
6401            // cross-profile app linking works only towards the parent.
6402            final int callingUid = Binder.getCallingUid();
6403            final UserInfo parent = getProfileParent(sourceUserId);
6404            synchronized(mPackages) {
6405                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6406                        false /*includeInstantApps*/);
6407                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6408                        intent, resolvedType, flags, sourceUserId, parent.id);
6409                return xpDomainInfo != null;
6410            }
6411        }
6412        return false;
6413    }
6414
6415    private UserInfo getProfileParent(int userId) {
6416        final long identity = Binder.clearCallingIdentity();
6417        try {
6418            return sUserManager.getProfileParent(userId);
6419        } finally {
6420            Binder.restoreCallingIdentity(identity);
6421        }
6422    }
6423
6424    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6425            String resolvedType, int userId) {
6426        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6427        if (resolver != null) {
6428            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6429        }
6430        return null;
6431    }
6432
6433    @Override
6434    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6435            String resolvedType, int flags, int userId) {
6436        try {
6437            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6438
6439            return new ParceledListSlice<>(
6440                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6441        } finally {
6442            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6443        }
6444    }
6445
6446    /**
6447     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6448     * instant, returns {@code null}.
6449     */
6450    private String getInstantAppPackageName(int callingUid) {
6451        synchronized (mPackages) {
6452            // If the caller is an isolated app use the owner's uid for the lookup.
6453            if (Process.isIsolated(callingUid)) {
6454                callingUid = mIsolatedOwners.get(callingUid);
6455            }
6456            final int appId = UserHandle.getAppId(callingUid);
6457            final Object obj = mSettings.getUserIdLPr(appId);
6458            if (obj instanceof PackageSetting) {
6459                final PackageSetting ps = (PackageSetting) obj;
6460                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6461                return isInstantApp ? ps.pkg.packageName : null;
6462            }
6463        }
6464        return null;
6465    }
6466
6467    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6468            String resolvedType, int flags, int userId) {
6469        return queryIntentActivitiesInternal(
6470                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6471                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6472    }
6473
6474    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6475            String resolvedType, int flags, int filterCallingUid, int userId,
6476            boolean resolveForStart, boolean allowDynamicSplits) {
6477        if (!sUserManager.exists(userId)) return Collections.emptyList();
6478        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6479        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6480                false /* requireFullPermission */, false /* checkShell */,
6481                "query intent activities");
6482        final String pkgName = intent.getPackage();
6483        ComponentName comp = intent.getComponent();
6484        if (comp == null) {
6485            if (intent.getSelector() != null) {
6486                intent = intent.getSelector();
6487                comp = intent.getComponent();
6488            }
6489        }
6490
6491        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6492                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6493        if (comp != null) {
6494            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6495            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6496            if (ai != null) {
6497                // When specifying an explicit component, we prevent the activity from being
6498                // used when either 1) the calling package is normal and the activity is within
6499                // an ephemeral application or 2) the calling package is ephemeral and the
6500                // activity is not visible to ephemeral applications.
6501                final boolean matchInstantApp =
6502                        (flags & PackageManager.MATCH_INSTANT) != 0;
6503                final boolean matchVisibleToInstantAppOnly =
6504                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6505                final boolean matchExplicitlyVisibleOnly =
6506                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6507                final boolean isCallerInstantApp =
6508                        instantAppPkgName != null;
6509                final boolean isTargetSameInstantApp =
6510                        comp.getPackageName().equals(instantAppPkgName);
6511                final boolean isTargetInstantApp =
6512                        (ai.applicationInfo.privateFlags
6513                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6514                final boolean isTargetVisibleToInstantApp =
6515                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6516                final boolean isTargetExplicitlyVisibleToInstantApp =
6517                        isTargetVisibleToInstantApp
6518                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6519                final boolean isTargetHiddenFromInstantApp =
6520                        !isTargetVisibleToInstantApp
6521                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6522                final boolean blockResolution =
6523                        !isTargetSameInstantApp
6524                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6525                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6526                                        && isTargetHiddenFromInstantApp));
6527                if (!blockResolution) {
6528                    final ResolveInfo ri = new ResolveInfo();
6529                    ri.activityInfo = ai;
6530                    list.add(ri);
6531                }
6532            }
6533            return applyPostResolutionFilter(
6534                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6535        }
6536
6537        // reader
6538        boolean sortResult = false;
6539        boolean addInstant = false;
6540        List<ResolveInfo> result;
6541        synchronized (mPackages) {
6542            if (pkgName == null) {
6543                List<CrossProfileIntentFilter> matchingFilters =
6544                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6545                // Check for results that need to skip the current profile.
6546                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6547                        resolvedType, flags, userId);
6548                if (xpResolveInfo != null) {
6549                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6550                    xpResult.add(xpResolveInfo);
6551                    return applyPostResolutionFilter(
6552                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6553                            allowDynamicSplits, filterCallingUid, userId, intent);
6554                }
6555
6556                // Check for results in the current profile.
6557                result = filterIfNotSystemUser(mActivities.queryIntent(
6558                        intent, resolvedType, flags, userId), userId);
6559                addInstant = isInstantAppResolutionAllowed(intent, result, userId,
6560                        false /*skipPackageCheck*/);
6561                // Check for cross profile results.
6562                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6563                xpResolveInfo = queryCrossProfileIntents(
6564                        matchingFilters, intent, resolvedType, flags, userId,
6565                        hasNonNegativePriorityResult);
6566                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6567                    boolean isVisibleToUser = filterIfNotSystemUser(
6568                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6569                    if (isVisibleToUser) {
6570                        result.add(xpResolveInfo);
6571                        sortResult = true;
6572                    }
6573                }
6574                if (intent.hasWebURI()) {
6575                    CrossProfileDomainInfo xpDomainInfo = null;
6576                    final UserInfo parent = getProfileParent(userId);
6577                    if (parent != null) {
6578                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6579                                flags, userId, parent.id);
6580                    }
6581                    if (xpDomainInfo != null) {
6582                        if (xpResolveInfo != null) {
6583                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6584                            // in the result.
6585                            result.remove(xpResolveInfo);
6586                        }
6587                        if (result.size() == 0 && !addInstant) {
6588                            // No result in current profile, but found candidate in parent user.
6589                            // And we are not going to add emphemeral app, so we can return the
6590                            // result straight away.
6591                            result.add(xpDomainInfo.resolveInfo);
6592                            return applyPostResolutionFilter(result, instantAppPkgName,
6593                                    allowDynamicSplits, filterCallingUid, userId, intent);
6594                        }
6595                    } else if (result.size() <= 1 && !addInstant) {
6596                        // No result in parent user and <= 1 result in current profile, and we
6597                        // are not going to add emphemeral app, so we can return the result without
6598                        // further processing.
6599                        return applyPostResolutionFilter(result, instantAppPkgName,
6600                                allowDynamicSplits, filterCallingUid, userId, intent);
6601                    }
6602                    // We have more than one candidate (combining results from current and parent
6603                    // profile), so we need filtering and sorting.
6604                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6605                            intent, flags, result, xpDomainInfo, userId);
6606                    sortResult = true;
6607                }
6608            } else {
6609                final PackageParser.Package pkg = mPackages.get(pkgName);
6610                result = null;
6611                if (pkg != null) {
6612                    result = filterIfNotSystemUser(
6613                            mActivities.queryIntentForPackage(
6614                                    intent, resolvedType, flags, pkg.activities, userId),
6615                            userId);
6616                }
6617                if (result == null || result.size() == 0) {
6618                    // the caller wants to resolve for a particular package; however, there
6619                    // were no installed results, so, try to find an ephemeral result
6620                    addInstant = isInstantAppResolutionAllowed(
6621                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6622                    if (result == null) {
6623                        result = new ArrayList<>();
6624                    }
6625                }
6626            }
6627        }
6628        if (addInstant) {
6629            result = maybeAddInstantAppInstaller(
6630                    result, intent, resolvedType, flags, userId, resolveForStart);
6631        }
6632        if (sortResult) {
6633            Collections.sort(result, mResolvePrioritySorter);
6634        }
6635        return applyPostResolutionFilter(
6636                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6637    }
6638
6639    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6640            String resolvedType, int flags, int userId, boolean resolveForStart) {
6641        // first, check to see if we've got an instant app already installed
6642        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6643        ResolveInfo localInstantApp = null;
6644        boolean blockResolution = false;
6645        if (!alreadyResolvedLocally) {
6646            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6647                    flags
6648                        | PackageManager.GET_RESOLVED_FILTER
6649                        | PackageManager.MATCH_INSTANT
6650                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6651                    userId);
6652            for (int i = instantApps.size() - 1; i >= 0; --i) {
6653                final ResolveInfo info = instantApps.get(i);
6654                final String packageName = info.activityInfo.packageName;
6655                final PackageSetting ps = mSettings.mPackages.get(packageName);
6656                if (ps.getInstantApp(userId)) {
6657                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6658                    final int status = (int)(packedStatus >> 32);
6659                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6660                        // there's a local instant application installed, but, the user has
6661                        // chosen to never use it; skip resolution and don't acknowledge
6662                        // an instant application is even available
6663                        if (DEBUG_INSTANT) {
6664                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6665                        }
6666                        blockResolution = true;
6667                        break;
6668                    } else {
6669                        // we have a locally installed instant application; skip resolution
6670                        // but acknowledge there's an instant application available
6671                        if (DEBUG_INSTANT) {
6672                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6673                        }
6674                        localInstantApp = info;
6675                        break;
6676                    }
6677                }
6678            }
6679        }
6680        // no app installed, let's see if one's available
6681        AuxiliaryResolveInfo auxiliaryResponse = null;
6682        if (!blockResolution) {
6683            if (localInstantApp == null) {
6684                // we don't have an instant app locally, resolve externally
6685                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6686                final InstantAppRequest requestObject = new InstantAppRequest(
6687                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6688                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6689                        resolveForStart);
6690                auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne(
6691                        mInstantAppResolverConnection, requestObject);
6692                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6693            } else {
6694                // we have an instant application locally, but, we can't admit that since
6695                // callers shouldn't be able to determine prior browsing. create a dummy
6696                // auxiliary response so the downstream code behaves as if there's an
6697                // instant application available externally. when it comes time to start
6698                // the instant application, we'll do the right thing.
6699                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6700                auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */,
6701                                        ai.packageName, ai.versionCode, null /* splitName */);
6702            }
6703        }
6704        if (intent.isWebIntent() && auxiliaryResponse == null) {
6705            return result;
6706        }
6707        final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6708        if (ps == null
6709                || ps.getUserState().get(userId) == null
6710                || !ps.getUserState().get(userId).isEnabled(mInstantAppInstallerActivity, 0)) {
6711            return result;
6712        }
6713        final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6714        ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6715                mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6716        ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6717                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6718        // add a non-generic filter
6719        ephemeralInstaller.filter = new IntentFilter();
6720        if (intent.getAction() != null) {
6721            ephemeralInstaller.filter.addAction(intent.getAction());
6722        }
6723        if (intent.getData() != null && intent.getData().getPath() != null) {
6724            ephemeralInstaller.filter.addDataPath(
6725                    intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6726        }
6727        ephemeralInstaller.isInstantAppAvailable = true;
6728        // make sure this resolver is the default
6729        ephemeralInstaller.isDefault = true;
6730        ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6731        if (DEBUG_INSTANT) {
6732            Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6733        }
6734
6735        result.add(ephemeralInstaller);
6736        return result;
6737    }
6738
6739    private static class CrossProfileDomainInfo {
6740        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6741        ResolveInfo resolveInfo;
6742        /* Best domain verification status of the activities found in the other profile */
6743        int bestDomainVerificationStatus;
6744    }
6745
6746    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6747            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6748        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6749                sourceUserId)) {
6750            return null;
6751        }
6752        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6753                resolvedType, flags, parentUserId);
6754
6755        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6756            return null;
6757        }
6758        CrossProfileDomainInfo result = null;
6759        int size = resultTargetUser.size();
6760        for (int i = 0; i < size; i++) {
6761            ResolveInfo riTargetUser = resultTargetUser.get(i);
6762            // Intent filter verification is only for filters that specify a host. So don't return
6763            // those that handle all web uris.
6764            if (riTargetUser.handleAllWebDataURI) {
6765                continue;
6766            }
6767            String packageName = riTargetUser.activityInfo.packageName;
6768            PackageSetting ps = mSettings.mPackages.get(packageName);
6769            if (ps == null) {
6770                continue;
6771            }
6772            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6773            int status = (int)(verificationState >> 32);
6774            if (result == null) {
6775                result = new CrossProfileDomainInfo();
6776                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6777                        sourceUserId, parentUserId);
6778                result.bestDomainVerificationStatus = status;
6779            } else {
6780                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6781                        result.bestDomainVerificationStatus);
6782            }
6783        }
6784        // Don't consider matches with status NEVER across profiles.
6785        if (result != null && result.bestDomainVerificationStatus
6786                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6787            return null;
6788        }
6789        return result;
6790    }
6791
6792    /**
6793     * Verification statuses are ordered from the worse to the best, except for
6794     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6795     */
6796    private int bestDomainVerificationStatus(int status1, int status2) {
6797        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6798            return status2;
6799        }
6800        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6801            return status1;
6802        }
6803        return (int) MathUtils.max(status1, status2);
6804    }
6805
6806    private boolean isUserEnabled(int userId) {
6807        long callingId = Binder.clearCallingIdentity();
6808        try {
6809            UserInfo userInfo = sUserManager.getUserInfo(userId);
6810            return userInfo != null && userInfo.isEnabled();
6811        } finally {
6812            Binder.restoreCallingIdentity(callingId);
6813        }
6814    }
6815
6816    /**
6817     * Filter out activities with systemUserOnly flag set, when current user is not System.
6818     *
6819     * @return filtered list
6820     */
6821    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6822        if (userId == UserHandle.USER_SYSTEM) {
6823            return resolveInfos;
6824        }
6825        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6826            ResolveInfo info = resolveInfos.get(i);
6827            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6828                resolveInfos.remove(i);
6829            }
6830        }
6831        return resolveInfos;
6832    }
6833
6834    /**
6835     * Filters out ephemeral activities.
6836     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6837     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6838     *
6839     * @param resolveInfos The pre-filtered list of resolved activities
6840     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6841     *          is performed.
6842     * @param intent
6843     * @return A filtered list of resolved activities.
6844     */
6845    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6846            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId,
6847            Intent intent) {
6848        final boolean blockInstant = intent.isWebIntent() && areWebInstantAppsDisabled();
6849        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6850            final ResolveInfo info = resolveInfos.get(i);
6851            // remove locally resolved instant app web results when disabled
6852            if (info.isInstantAppAvailable && blockInstant) {
6853                resolveInfos.remove(i);
6854                continue;
6855            }
6856            // allow activities that are defined in the provided package
6857            if (allowDynamicSplits
6858                    && info.activityInfo != null
6859                    && info.activityInfo.splitName != null
6860                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6861                            info.activityInfo.splitName)) {
6862                if (mInstantAppInstallerActivity == null) {
6863                    if (DEBUG_INSTALL) {
6864                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6865                    }
6866                    resolveInfos.remove(i);
6867                    continue;
6868                }
6869                if (blockInstant && isInstantApp(info.activityInfo.packageName, userId)) {
6870                    resolveInfos.remove(i);
6871                    continue;
6872                }
6873                // requested activity is defined in a split that hasn't been installed yet.
6874                // add the installer to the resolve list
6875                if (DEBUG_INSTALL) {
6876                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6877                }
6878                final ResolveInfo installerInfo = new ResolveInfo(
6879                        mInstantAppInstallerInfo);
6880                final ComponentName installFailureActivity = findInstallFailureActivity(
6881                        info.activityInfo.packageName,  filterCallingUid, userId);
6882                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6883                        installFailureActivity,
6884                        info.activityInfo.packageName,
6885                        info.activityInfo.applicationInfo.versionCode,
6886                        info.activityInfo.splitName);
6887                // add a non-generic filter
6888                installerInfo.filter = new IntentFilter();
6889
6890                // This resolve info may appear in the chooser UI, so let us make it
6891                // look as the one it replaces as far as the user is concerned which
6892                // requires loading the correct label and icon for the resolve info.
6893                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6894                installerInfo.labelRes = info.resolveLabelResId();
6895                installerInfo.icon = info.resolveIconResId();
6896                installerInfo.isInstantAppAvailable = true;
6897                resolveInfos.set(i, installerInfo);
6898                continue;
6899            }
6900            // caller is a full app, don't need to apply any other filtering
6901            if (ephemeralPkgName == null) {
6902                continue;
6903            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6904                // caller is same app; don't need to apply any other filtering
6905                continue;
6906            }
6907            // allow activities that have been explicitly exposed to ephemeral apps
6908            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6909            if (!isEphemeralApp
6910                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6911                continue;
6912            }
6913            resolveInfos.remove(i);
6914        }
6915        return resolveInfos;
6916    }
6917
6918    /**
6919     * Returns the activity component that can handle install failures.
6920     * <p>By default, the instant application installer handles failures. However, an
6921     * application may want to handle failures on its own. Applications do this by
6922     * creating an activity with an intent filter that handles the action
6923     * {@link Intent#ACTION_INSTALL_FAILURE}.
6924     */
6925    private @Nullable ComponentName findInstallFailureActivity(
6926            String packageName, int filterCallingUid, int userId) {
6927        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6928        failureActivityIntent.setPackage(packageName);
6929        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6930        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6931                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6932                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6933        final int NR = result.size();
6934        if (NR > 0) {
6935            for (int i = 0; i < NR; i++) {
6936                final ResolveInfo info = result.get(i);
6937                if (info.activityInfo.splitName != null) {
6938                    continue;
6939                }
6940                return new ComponentName(packageName, info.activityInfo.name);
6941            }
6942        }
6943        return null;
6944    }
6945
6946    /**
6947     * @param resolveInfos list of resolve infos in descending priority order
6948     * @return if the list contains a resolve info with non-negative priority
6949     */
6950    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6951        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6952    }
6953
6954    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6955            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6956            int userId) {
6957        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6958
6959        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6960            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6961                    candidates.size());
6962        }
6963
6964        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6965        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6966        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6967        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6968        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6969        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6970
6971        synchronized (mPackages) {
6972            final int count = candidates.size();
6973            // First, try to use linked apps. Partition the candidates into four lists:
6974            // one for the final results, one for the "do not use ever", one for "undefined status"
6975            // and finally one for "browser app type".
6976            for (int n=0; n<count; n++) {
6977                ResolveInfo info = candidates.get(n);
6978                String packageName = info.activityInfo.packageName;
6979                PackageSetting ps = mSettings.mPackages.get(packageName);
6980                if (ps != null) {
6981                    // Add to the special match all list (Browser use case)
6982                    if (info.handleAllWebDataURI) {
6983                        matchAllList.add(info);
6984                        continue;
6985                    }
6986                    // Try to get the status from User settings first
6987                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6988                    int status = (int)(packedStatus >> 32);
6989                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6990                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6991                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6992                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6993                                    + " : linkgen=" + linkGeneration);
6994                        }
6995                        // Use link-enabled generation as preferredOrder, i.e.
6996                        // prefer newly-enabled over earlier-enabled.
6997                        info.preferredOrder = linkGeneration;
6998                        alwaysList.add(info);
6999                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7000                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7001                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7002                        }
7003                        neverList.add(info);
7004                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7005                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7006                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7007                        }
7008                        alwaysAskList.add(info);
7009                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7010                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7011                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7012                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7013                        }
7014                        undefinedList.add(info);
7015                    }
7016                }
7017            }
7018
7019            // We'll want to include browser possibilities in a few cases
7020            boolean includeBrowser = false;
7021
7022            // First try to add the "always" resolution(s) for the current user, if any
7023            if (alwaysList.size() > 0) {
7024                result.addAll(alwaysList);
7025            } else {
7026                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7027                result.addAll(undefinedList);
7028                // Maybe add one for the other profile.
7029                if (xpDomainInfo != null && (
7030                        xpDomainInfo.bestDomainVerificationStatus
7031                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7032                    result.add(xpDomainInfo.resolveInfo);
7033                }
7034                includeBrowser = true;
7035            }
7036
7037            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7038            // If there were 'always' entries their preferred order has been set, so we also
7039            // back that off to make the alternatives equivalent
7040            if (alwaysAskList.size() > 0) {
7041                for (ResolveInfo i : result) {
7042                    i.preferredOrder = 0;
7043                }
7044                result.addAll(alwaysAskList);
7045                includeBrowser = true;
7046            }
7047
7048            if (includeBrowser) {
7049                // Also add browsers (all of them or only the default one)
7050                if (DEBUG_DOMAIN_VERIFICATION) {
7051                    Slog.v(TAG, "   ...including browsers in candidate set");
7052                }
7053                if ((matchFlags & MATCH_ALL) != 0) {
7054                    result.addAll(matchAllList);
7055                } else {
7056                    // Browser/generic handling case.  If there's a default browser, go straight
7057                    // to that (but only if there is no other higher-priority match).
7058                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7059                    int maxMatchPrio = 0;
7060                    ResolveInfo defaultBrowserMatch = null;
7061                    final int numCandidates = matchAllList.size();
7062                    for (int n = 0; n < numCandidates; n++) {
7063                        ResolveInfo info = matchAllList.get(n);
7064                        // track the highest overall match priority...
7065                        if (info.priority > maxMatchPrio) {
7066                            maxMatchPrio = info.priority;
7067                        }
7068                        // ...and the highest-priority default browser match
7069                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7070                            if (defaultBrowserMatch == null
7071                                    || (defaultBrowserMatch.priority < info.priority)) {
7072                                if (debug) {
7073                                    Slog.v(TAG, "Considering default browser match " + info);
7074                                }
7075                                defaultBrowserMatch = info;
7076                            }
7077                        }
7078                    }
7079                    if (defaultBrowserMatch != null
7080                            && defaultBrowserMatch.priority >= maxMatchPrio
7081                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7082                    {
7083                        if (debug) {
7084                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7085                        }
7086                        result.add(defaultBrowserMatch);
7087                    } else {
7088                        result.addAll(matchAllList);
7089                    }
7090                }
7091
7092                // If there is nothing selected, add all candidates and remove the ones that the user
7093                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7094                if (result.size() == 0) {
7095                    result.addAll(candidates);
7096                    result.removeAll(neverList);
7097                }
7098            }
7099        }
7100        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7101            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7102                    result.size());
7103            for (ResolveInfo info : result) {
7104                Slog.v(TAG, "  + " + info.activityInfo);
7105            }
7106        }
7107        return result;
7108    }
7109
7110    // Returns a packed value as a long:
7111    //
7112    // high 'int'-sized word: link status: undefined/ask/never/always.
7113    // low 'int'-sized word: relative priority among 'always' results.
7114    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7115        long result = ps.getDomainVerificationStatusForUser(userId);
7116        // if none available, get the master status
7117        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7118            if (ps.getIntentFilterVerificationInfo() != null) {
7119                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7120            }
7121        }
7122        return result;
7123    }
7124
7125    private ResolveInfo querySkipCurrentProfileIntents(
7126            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7127            int flags, int sourceUserId) {
7128        if (matchingFilters != null) {
7129            int size = matchingFilters.size();
7130            for (int i = 0; i < size; i ++) {
7131                CrossProfileIntentFilter filter = matchingFilters.get(i);
7132                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7133                    // Checking if there are activities in the target user that can handle the
7134                    // intent.
7135                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7136                            resolvedType, flags, sourceUserId);
7137                    if (resolveInfo != null) {
7138                        return resolveInfo;
7139                    }
7140                }
7141            }
7142        }
7143        return null;
7144    }
7145
7146    // Return matching ResolveInfo in target user if any.
7147    private ResolveInfo queryCrossProfileIntents(
7148            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7149            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7150        if (matchingFilters != null) {
7151            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7152            // match the same intent. For performance reasons, it is better not to
7153            // run queryIntent twice for the same userId
7154            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7155            int size = matchingFilters.size();
7156            for (int i = 0; i < size; i++) {
7157                CrossProfileIntentFilter filter = matchingFilters.get(i);
7158                int targetUserId = filter.getTargetUserId();
7159                boolean skipCurrentProfile =
7160                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7161                boolean skipCurrentProfileIfNoMatchFound =
7162                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7163                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7164                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7165                    // Checking if there are activities in the target user that can handle the
7166                    // intent.
7167                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7168                            resolvedType, flags, sourceUserId);
7169                    if (resolveInfo != null) return resolveInfo;
7170                    alreadyTriedUserIds.put(targetUserId, true);
7171                }
7172            }
7173        }
7174        return null;
7175    }
7176
7177    /**
7178     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7179     * will forward the intent to the filter's target user.
7180     * Otherwise, returns null.
7181     */
7182    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7183            String resolvedType, int flags, int sourceUserId) {
7184        int targetUserId = filter.getTargetUserId();
7185        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7186                resolvedType, flags, targetUserId);
7187        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7188            // If all the matches in the target profile are suspended, return null.
7189            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7190                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7191                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7192                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7193                            targetUserId);
7194                }
7195            }
7196        }
7197        return null;
7198    }
7199
7200    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7201            int sourceUserId, int targetUserId) {
7202        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7203        long ident = Binder.clearCallingIdentity();
7204        boolean targetIsProfile;
7205        try {
7206            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7207        } finally {
7208            Binder.restoreCallingIdentity(ident);
7209        }
7210        String className;
7211        if (targetIsProfile) {
7212            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7213        } else {
7214            className = FORWARD_INTENT_TO_PARENT;
7215        }
7216        ComponentName forwardingActivityComponentName = new ComponentName(
7217                mAndroidApplication.packageName, className);
7218        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7219                sourceUserId);
7220        if (!targetIsProfile) {
7221            forwardingActivityInfo.showUserIcon = targetUserId;
7222            forwardingResolveInfo.noResourceId = true;
7223        }
7224        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7225        forwardingResolveInfo.priority = 0;
7226        forwardingResolveInfo.preferredOrder = 0;
7227        forwardingResolveInfo.match = 0;
7228        forwardingResolveInfo.isDefault = true;
7229        forwardingResolveInfo.filter = filter;
7230        forwardingResolveInfo.targetUserId = targetUserId;
7231        return forwardingResolveInfo;
7232    }
7233
7234    @Override
7235    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7236            Intent[] specifics, String[] specificTypes, Intent intent,
7237            String resolvedType, int flags, int userId) {
7238        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7239                specificTypes, intent, resolvedType, flags, userId));
7240    }
7241
7242    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7243            Intent[] specifics, String[] specificTypes, Intent intent,
7244            String resolvedType, int flags, int userId) {
7245        if (!sUserManager.exists(userId)) return Collections.emptyList();
7246        final int callingUid = Binder.getCallingUid();
7247        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7248                false /*includeInstantApps*/);
7249        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7250                false /*requireFullPermission*/, false /*checkShell*/,
7251                "query intent activity options");
7252        final String resultsAction = intent.getAction();
7253
7254        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7255                | PackageManager.GET_RESOLVED_FILTER, userId);
7256
7257        if (DEBUG_INTENT_MATCHING) {
7258            Log.v(TAG, "Query " + intent + ": " + results);
7259        }
7260
7261        int specificsPos = 0;
7262        int N;
7263
7264        // todo: note that the algorithm used here is O(N^2).  This
7265        // isn't a problem in our current environment, but if we start running
7266        // into situations where we have more than 5 or 10 matches then this
7267        // should probably be changed to something smarter...
7268
7269        // First we go through and resolve each of the specific items
7270        // that were supplied, taking care of removing any corresponding
7271        // duplicate items in the generic resolve list.
7272        if (specifics != null) {
7273            for (int i=0; i<specifics.length; i++) {
7274                final Intent sintent = specifics[i];
7275                if (sintent == null) {
7276                    continue;
7277                }
7278
7279                if (DEBUG_INTENT_MATCHING) {
7280                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7281                }
7282
7283                String action = sintent.getAction();
7284                if (resultsAction != null && resultsAction.equals(action)) {
7285                    // If this action was explicitly requested, then don't
7286                    // remove things that have it.
7287                    action = null;
7288                }
7289
7290                ResolveInfo ri = null;
7291                ActivityInfo ai = null;
7292
7293                ComponentName comp = sintent.getComponent();
7294                if (comp == null) {
7295                    ri = resolveIntent(
7296                        sintent,
7297                        specificTypes != null ? specificTypes[i] : null,
7298                            flags, userId);
7299                    if (ri == null) {
7300                        continue;
7301                    }
7302                    if (ri == mResolveInfo) {
7303                        // ACK!  Must do something better with this.
7304                    }
7305                    ai = ri.activityInfo;
7306                    comp = new ComponentName(ai.applicationInfo.packageName,
7307                            ai.name);
7308                } else {
7309                    ai = getActivityInfo(comp, flags, userId);
7310                    if (ai == null) {
7311                        continue;
7312                    }
7313                }
7314
7315                // Look for any generic query activities that are duplicates
7316                // of this specific one, and remove them from the results.
7317                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7318                N = results.size();
7319                int j;
7320                for (j=specificsPos; j<N; j++) {
7321                    ResolveInfo sri = results.get(j);
7322                    if ((sri.activityInfo.name.equals(comp.getClassName())
7323                            && sri.activityInfo.applicationInfo.packageName.equals(
7324                                    comp.getPackageName()))
7325                        || (action != null && sri.filter.matchAction(action))) {
7326                        results.remove(j);
7327                        if (DEBUG_INTENT_MATCHING) Log.v(
7328                            TAG, "Removing duplicate item from " + j
7329                            + " due to specific " + specificsPos);
7330                        if (ri == null) {
7331                            ri = sri;
7332                        }
7333                        j--;
7334                        N--;
7335                    }
7336                }
7337
7338                // Add this specific item to its proper place.
7339                if (ri == null) {
7340                    ri = new ResolveInfo();
7341                    ri.activityInfo = ai;
7342                }
7343                results.add(specificsPos, ri);
7344                ri.specificIndex = i;
7345                specificsPos++;
7346            }
7347        }
7348
7349        // Now we go through the remaining generic results and remove any
7350        // duplicate actions that are found here.
7351        N = results.size();
7352        for (int i=specificsPos; i<N-1; i++) {
7353            final ResolveInfo rii = results.get(i);
7354            if (rii.filter == null) {
7355                continue;
7356            }
7357
7358            // Iterate over all of the actions of this result's intent
7359            // filter...  typically this should be just one.
7360            final Iterator<String> it = rii.filter.actionsIterator();
7361            if (it == null) {
7362                continue;
7363            }
7364            while (it.hasNext()) {
7365                final String action = it.next();
7366                if (resultsAction != null && resultsAction.equals(action)) {
7367                    // If this action was explicitly requested, then don't
7368                    // remove things that have it.
7369                    continue;
7370                }
7371                for (int j=i+1; j<N; j++) {
7372                    final ResolveInfo rij = results.get(j);
7373                    if (rij.filter != null && rij.filter.hasAction(action)) {
7374                        results.remove(j);
7375                        if (DEBUG_INTENT_MATCHING) Log.v(
7376                            TAG, "Removing duplicate item from " + j
7377                            + " due to action " + action + " at " + i);
7378                        j--;
7379                        N--;
7380                    }
7381                }
7382            }
7383
7384            // If the caller didn't request filter information, drop it now
7385            // so we don't have to marshall/unmarshall it.
7386            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7387                rii.filter = null;
7388            }
7389        }
7390
7391        // Filter out the caller activity if so requested.
7392        if (caller != null) {
7393            N = results.size();
7394            for (int i=0; i<N; i++) {
7395                ActivityInfo ainfo = results.get(i).activityInfo;
7396                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7397                        && caller.getClassName().equals(ainfo.name)) {
7398                    results.remove(i);
7399                    break;
7400                }
7401            }
7402        }
7403
7404        // If the caller didn't request filter information,
7405        // drop them now so we don't have to
7406        // marshall/unmarshall it.
7407        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7408            N = results.size();
7409            for (int i=0; i<N; i++) {
7410                results.get(i).filter = null;
7411            }
7412        }
7413
7414        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7415        return results;
7416    }
7417
7418    @Override
7419    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7420            String resolvedType, int flags, int userId) {
7421        return new ParceledListSlice<>(
7422                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7423                        false /*allowDynamicSplits*/));
7424    }
7425
7426    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7427            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7428        if (!sUserManager.exists(userId)) return Collections.emptyList();
7429        final int callingUid = Binder.getCallingUid();
7430        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7431                false /*requireFullPermission*/, false /*checkShell*/,
7432                "query intent receivers");
7433        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7434        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7435                false /*includeInstantApps*/);
7436        ComponentName comp = intent.getComponent();
7437        if (comp == null) {
7438            if (intent.getSelector() != null) {
7439                intent = intent.getSelector();
7440                comp = intent.getComponent();
7441            }
7442        }
7443        if (comp != null) {
7444            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7445            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7446            if (ai != null) {
7447                // When specifying an explicit component, we prevent the activity from being
7448                // used when either 1) the calling package is normal and the activity is within
7449                // an instant application or 2) the calling package is ephemeral and the
7450                // activity is not visible to instant applications.
7451                final boolean matchInstantApp =
7452                        (flags & PackageManager.MATCH_INSTANT) != 0;
7453                final boolean matchVisibleToInstantAppOnly =
7454                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7455                final boolean matchExplicitlyVisibleOnly =
7456                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7457                final boolean isCallerInstantApp =
7458                        instantAppPkgName != null;
7459                final boolean isTargetSameInstantApp =
7460                        comp.getPackageName().equals(instantAppPkgName);
7461                final boolean isTargetInstantApp =
7462                        (ai.applicationInfo.privateFlags
7463                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7464                final boolean isTargetVisibleToInstantApp =
7465                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7466                final boolean isTargetExplicitlyVisibleToInstantApp =
7467                        isTargetVisibleToInstantApp
7468                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7469                final boolean isTargetHiddenFromInstantApp =
7470                        !isTargetVisibleToInstantApp
7471                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7472                final boolean blockResolution =
7473                        !isTargetSameInstantApp
7474                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7475                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7476                                        && isTargetHiddenFromInstantApp));
7477                if (!blockResolution) {
7478                    ResolveInfo ri = new ResolveInfo();
7479                    ri.activityInfo = ai;
7480                    list.add(ri);
7481                }
7482            }
7483            return applyPostResolutionFilter(
7484                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7485        }
7486
7487        // reader
7488        synchronized (mPackages) {
7489            String pkgName = intent.getPackage();
7490            if (pkgName == null) {
7491                final List<ResolveInfo> result =
7492                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7493                return applyPostResolutionFilter(
7494                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7495            }
7496            final PackageParser.Package pkg = mPackages.get(pkgName);
7497            if (pkg != null) {
7498                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7499                        intent, resolvedType, flags, pkg.receivers, userId);
7500                return applyPostResolutionFilter(
7501                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7502            }
7503            return Collections.emptyList();
7504        }
7505    }
7506
7507    @Override
7508    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7509        final int callingUid = Binder.getCallingUid();
7510        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7511    }
7512
7513    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7514            int userId, int callingUid) {
7515        if (!sUserManager.exists(userId)) return null;
7516        flags = updateFlagsForResolve(
7517                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7518        List<ResolveInfo> query = queryIntentServicesInternal(
7519                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7520        if (query != null) {
7521            if (query.size() >= 1) {
7522                // If there is more than one service with the same priority,
7523                // just arbitrarily pick the first one.
7524                return query.get(0);
7525            }
7526        }
7527        return null;
7528    }
7529
7530    @Override
7531    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7532            String resolvedType, int flags, int userId) {
7533        final int callingUid = Binder.getCallingUid();
7534        return new ParceledListSlice<>(queryIntentServicesInternal(
7535                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7536    }
7537
7538    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7539            String resolvedType, int flags, int userId, int callingUid,
7540            boolean includeInstantApps) {
7541        if (!sUserManager.exists(userId)) return Collections.emptyList();
7542        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7543                false /*requireFullPermission*/, false /*checkShell*/,
7544                "query intent receivers");
7545        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7546        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7547        ComponentName comp = intent.getComponent();
7548        if (comp == null) {
7549            if (intent.getSelector() != null) {
7550                intent = intent.getSelector();
7551                comp = intent.getComponent();
7552            }
7553        }
7554        if (comp != null) {
7555            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7556            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7557            if (si != null) {
7558                // When specifying an explicit component, we prevent the service from being
7559                // used when either 1) the service is in an instant application and the
7560                // caller is not the same instant application or 2) the calling package is
7561                // ephemeral and the activity is not visible to ephemeral applications.
7562                final boolean matchInstantApp =
7563                        (flags & PackageManager.MATCH_INSTANT) != 0;
7564                final boolean matchVisibleToInstantAppOnly =
7565                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7566                final boolean isCallerInstantApp =
7567                        instantAppPkgName != null;
7568                final boolean isTargetSameInstantApp =
7569                        comp.getPackageName().equals(instantAppPkgName);
7570                final boolean isTargetInstantApp =
7571                        (si.applicationInfo.privateFlags
7572                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7573                final boolean isTargetHiddenFromInstantApp =
7574                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7575                final boolean blockResolution =
7576                        !isTargetSameInstantApp
7577                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7578                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7579                                        && isTargetHiddenFromInstantApp));
7580                if (!blockResolution) {
7581                    final ResolveInfo ri = new ResolveInfo();
7582                    ri.serviceInfo = si;
7583                    list.add(ri);
7584                }
7585            }
7586            return list;
7587        }
7588
7589        // reader
7590        synchronized (mPackages) {
7591            String pkgName = intent.getPackage();
7592            if (pkgName == null) {
7593                return applyPostServiceResolutionFilter(
7594                        mServices.queryIntent(intent, resolvedType, flags, userId),
7595                        instantAppPkgName);
7596            }
7597            final PackageParser.Package pkg = mPackages.get(pkgName);
7598            if (pkg != null) {
7599                return applyPostServiceResolutionFilter(
7600                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7601                                userId),
7602                        instantAppPkgName);
7603            }
7604            return Collections.emptyList();
7605        }
7606    }
7607
7608    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7609            String instantAppPkgName) {
7610        if (instantAppPkgName == null) {
7611            return resolveInfos;
7612        }
7613        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7614            final ResolveInfo info = resolveInfos.get(i);
7615            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7616            // allow services that are defined in the provided package
7617            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7618                if (info.serviceInfo.splitName != null
7619                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7620                                info.serviceInfo.splitName)) {
7621                    // requested service is defined in a split that hasn't been installed yet.
7622                    // add the installer to the resolve list
7623                    if (DEBUG_INSTANT) {
7624                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7625                    }
7626                    final ResolveInfo installerInfo = new ResolveInfo(
7627                            mInstantAppInstallerInfo);
7628                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7629                            null /* installFailureActivity */,
7630                            info.serviceInfo.packageName,
7631                            info.serviceInfo.applicationInfo.versionCode,
7632                            info.serviceInfo.splitName);
7633                    // add a non-generic filter
7634                    installerInfo.filter = new IntentFilter();
7635                    // load resources from the correct package
7636                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7637                    resolveInfos.set(i, installerInfo);
7638                }
7639                continue;
7640            }
7641            // allow services that have been explicitly exposed to ephemeral apps
7642            if (!isEphemeralApp
7643                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7644                continue;
7645            }
7646            resolveInfos.remove(i);
7647        }
7648        return resolveInfos;
7649    }
7650
7651    @Override
7652    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7653            String resolvedType, int flags, int userId) {
7654        return new ParceledListSlice<>(
7655                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7656    }
7657
7658    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7659            Intent intent, String resolvedType, int flags, int userId) {
7660        if (!sUserManager.exists(userId)) return Collections.emptyList();
7661        final int callingUid = Binder.getCallingUid();
7662        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7663        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7664                false /*includeInstantApps*/);
7665        ComponentName comp = intent.getComponent();
7666        if (comp == null) {
7667            if (intent.getSelector() != null) {
7668                intent = intent.getSelector();
7669                comp = intent.getComponent();
7670            }
7671        }
7672        if (comp != null) {
7673            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7674            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7675            if (pi != null) {
7676                // When specifying an explicit component, we prevent the provider from being
7677                // used when either 1) the provider is in an instant application and the
7678                // caller is not the same instant application or 2) the calling package is an
7679                // instant application and the provider is not visible to instant applications.
7680                final boolean matchInstantApp =
7681                        (flags & PackageManager.MATCH_INSTANT) != 0;
7682                final boolean matchVisibleToInstantAppOnly =
7683                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7684                final boolean isCallerInstantApp =
7685                        instantAppPkgName != null;
7686                final boolean isTargetSameInstantApp =
7687                        comp.getPackageName().equals(instantAppPkgName);
7688                final boolean isTargetInstantApp =
7689                        (pi.applicationInfo.privateFlags
7690                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7691                final boolean isTargetHiddenFromInstantApp =
7692                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7693                final boolean blockResolution =
7694                        !isTargetSameInstantApp
7695                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7696                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7697                                        && isTargetHiddenFromInstantApp));
7698                if (!blockResolution) {
7699                    final ResolveInfo ri = new ResolveInfo();
7700                    ri.providerInfo = pi;
7701                    list.add(ri);
7702                }
7703            }
7704            return list;
7705        }
7706
7707        // reader
7708        synchronized (mPackages) {
7709            String pkgName = intent.getPackage();
7710            if (pkgName == null) {
7711                return applyPostContentProviderResolutionFilter(
7712                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7713                        instantAppPkgName);
7714            }
7715            final PackageParser.Package pkg = mPackages.get(pkgName);
7716            if (pkg != null) {
7717                return applyPostContentProviderResolutionFilter(
7718                        mProviders.queryIntentForPackage(
7719                        intent, resolvedType, flags, pkg.providers, userId),
7720                        instantAppPkgName);
7721            }
7722            return Collections.emptyList();
7723        }
7724    }
7725
7726    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7727            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7728        if (instantAppPkgName == null) {
7729            return resolveInfos;
7730        }
7731        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7732            final ResolveInfo info = resolveInfos.get(i);
7733            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7734            // allow providers that are defined in the provided package
7735            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7736                if (info.providerInfo.splitName != null
7737                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7738                                info.providerInfo.splitName)) {
7739                    // requested provider is defined in a split that hasn't been installed yet.
7740                    // add the installer to the resolve list
7741                    if (DEBUG_INSTANT) {
7742                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7743                    }
7744                    final ResolveInfo installerInfo = new ResolveInfo(
7745                            mInstantAppInstallerInfo);
7746                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7747                            null /*failureActivity*/,
7748                            info.providerInfo.packageName,
7749                            info.providerInfo.applicationInfo.versionCode,
7750                            info.providerInfo.splitName);
7751                    // add a non-generic filter
7752                    installerInfo.filter = new IntentFilter();
7753                    // load resources from the correct package
7754                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7755                    resolveInfos.set(i, installerInfo);
7756                }
7757                continue;
7758            }
7759            // allow providers that have been explicitly exposed to instant applications
7760            if (!isEphemeralApp
7761                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7762                continue;
7763            }
7764            resolveInfos.remove(i);
7765        }
7766        return resolveInfos;
7767    }
7768
7769    @Override
7770    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7771        final int callingUid = Binder.getCallingUid();
7772        if (getInstantAppPackageName(callingUid) != null) {
7773            return ParceledListSlice.emptyList();
7774        }
7775        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7776        flags = updateFlagsForPackage(flags, userId, null);
7777        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7778        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7779                true /* requireFullPermission */, false /* checkShell */,
7780                "get installed packages");
7781
7782        // writer
7783        synchronized (mPackages) {
7784            ArrayList<PackageInfo> list;
7785            if (listUninstalled) {
7786                list = new ArrayList<>(mSettings.mPackages.size());
7787                for (PackageSetting ps : mSettings.mPackages.values()) {
7788                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7789                        continue;
7790                    }
7791                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7792                        continue;
7793                    }
7794                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7795                    if (pi != null) {
7796                        list.add(pi);
7797                    }
7798                }
7799            } else {
7800                list = new ArrayList<>(mPackages.size());
7801                for (PackageParser.Package p : mPackages.values()) {
7802                    final PackageSetting ps = (PackageSetting) p.mExtras;
7803                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7804                        continue;
7805                    }
7806                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7807                        continue;
7808                    }
7809                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7810                            p.mExtras, flags, userId);
7811                    if (pi != null) {
7812                        list.add(pi);
7813                    }
7814                }
7815            }
7816
7817            return new ParceledListSlice<>(list);
7818        }
7819    }
7820
7821    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7822            String[] permissions, boolean[] tmp, int flags, int userId) {
7823        int numMatch = 0;
7824        final PermissionsState permissionsState = ps.getPermissionsState();
7825        for (int i=0; i<permissions.length; i++) {
7826            final String permission = permissions[i];
7827            if (permissionsState.hasPermission(permission, userId)) {
7828                tmp[i] = true;
7829                numMatch++;
7830            } else {
7831                tmp[i] = false;
7832            }
7833        }
7834        if (numMatch == 0) {
7835            return;
7836        }
7837        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7838
7839        // The above might return null in cases of uninstalled apps or install-state
7840        // skew across users/profiles.
7841        if (pi != null) {
7842            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7843                if (numMatch == permissions.length) {
7844                    pi.requestedPermissions = permissions;
7845                } else {
7846                    pi.requestedPermissions = new String[numMatch];
7847                    numMatch = 0;
7848                    for (int i=0; i<permissions.length; i++) {
7849                        if (tmp[i]) {
7850                            pi.requestedPermissions[numMatch] = permissions[i];
7851                            numMatch++;
7852                        }
7853                    }
7854                }
7855            }
7856            list.add(pi);
7857        }
7858    }
7859
7860    @Override
7861    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7862            String[] permissions, int flags, int userId) {
7863        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7864        flags = updateFlagsForPackage(flags, userId, permissions);
7865        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7866                true /* requireFullPermission */, false /* checkShell */,
7867                "get packages holding permissions");
7868        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7869
7870        // writer
7871        synchronized (mPackages) {
7872            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7873            boolean[] tmpBools = new boolean[permissions.length];
7874            if (listUninstalled) {
7875                for (PackageSetting ps : mSettings.mPackages.values()) {
7876                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7877                            userId);
7878                }
7879            } else {
7880                for (PackageParser.Package pkg : mPackages.values()) {
7881                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7882                    if (ps != null) {
7883                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7884                                userId);
7885                    }
7886                }
7887            }
7888
7889            return new ParceledListSlice<PackageInfo>(list);
7890        }
7891    }
7892
7893    @Override
7894    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7895        final int callingUid = Binder.getCallingUid();
7896        if (getInstantAppPackageName(callingUid) != null) {
7897            return ParceledListSlice.emptyList();
7898        }
7899        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7900        flags = updateFlagsForApplication(flags, userId, null);
7901        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7902
7903        // writer
7904        synchronized (mPackages) {
7905            ArrayList<ApplicationInfo> list;
7906            if (listUninstalled) {
7907                list = new ArrayList<>(mSettings.mPackages.size());
7908                for (PackageSetting ps : mSettings.mPackages.values()) {
7909                    ApplicationInfo ai;
7910                    int effectiveFlags = flags;
7911                    if (ps.isSystem()) {
7912                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7913                    }
7914                    if (ps.pkg != null) {
7915                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7916                            continue;
7917                        }
7918                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7919                            continue;
7920                        }
7921                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7922                                ps.readUserState(userId), userId);
7923                        if (ai != null) {
7924                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7925                        }
7926                    } else {
7927                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7928                        // and already converts to externally visible package name
7929                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7930                                callingUid, effectiveFlags, userId);
7931                    }
7932                    if (ai != null) {
7933                        list.add(ai);
7934                    }
7935                }
7936            } else {
7937                list = new ArrayList<>(mPackages.size());
7938                for (PackageParser.Package p : mPackages.values()) {
7939                    if (p.mExtras != null) {
7940                        PackageSetting ps = (PackageSetting) p.mExtras;
7941                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7942                            continue;
7943                        }
7944                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7945                            continue;
7946                        }
7947                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7948                                ps.readUserState(userId), userId);
7949                        if (ai != null) {
7950                            ai.packageName = resolveExternalPackageNameLPr(p);
7951                            list.add(ai);
7952                        }
7953                    }
7954                }
7955            }
7956
7957            return new ParceledListSlice<>(list);
7958        }
7959    }
7960
7961    @Override
7962    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7963        if (HIDE_EPHEMERAL_APIS) {
7964            return null;
7965        }
7966        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7967            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7968                    "getEphemeralApplications");
7969        }
7970        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7971                true /* requireFullPermission */, false /* checkShell */,
7972                "getEphemeralApplications");
7973        synchronized (mPackages) {
7974            List<InstantAppInfo> instantApps = mInstantAppRegistry
7975                    .getInstantAppsLPr(userId);
7976            if (instantApps != null) {
7977                return new ParceledListSlice<>(instantApps);
7978            }
7979        }
7980        return null;
7981    }
7982
7983    @Override
7984    public boolean isInstantApp(String packageName, int userId) {
7985        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7986                true /* requireFullPermission */, false /* checkShell */,
7987                "isInstantApp");
7988        if (HIDE_EPHEMERAL_APIS) {
7989            return false;
7990        }
7991
7992        synchronized (mPackages) {
7993            int callingUid = Binder.getCallingUid();
7994            if (Process.isIsolated(callingUid)) {
7995                callingUid = mIsolatedOwners.get(callingUid);
7996            }
7997            final PackageSetting ps = mSettings.mPackages.get(packageName);
7998            PackageParser.Package pkg = mPackages.get(packageName);
7999            final boolean returnAllowed =
8000                    ps != null
8001                    && (isCallerSameApp(packageName, callingUid)
8002                            || canViewInstantApps(callingUid, userId)
8003                            || mInstantAppRegistry.isInstantAccessGranted(
8004                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8005            if (returnAllowed) {
8006                return ps.getInstantApp(userId);
8007            }
8008        }
8009        return false;
8010    }
8011
8012    @Override
8013    public byte[] getInstantAppCookie(String packageName, int userId) {
8014        if (HIDE_EPHEMERAL_APIS) {
8015            return null;
8016        }
8017
8018        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8019                true /* requireFullPermission */, false /* checkShell */,
8020                "getInstantAppCookie");
8021        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8022            return null;
8023        }
8024        synchronized (mPackages) {
8025            return mInstantAppRegistry.getInstantAppCookieLPw(
8026                    packageName, userId);
8027        }
8028    }
8029
8030    @Override
8031    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8032        if (HIDE_EPHEMERAL_APIS) {
8033            return true;
8034        }
8035
8036        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8037                true /* requireFullPermission */, true /* checkShell */,
8038                "setInstantAppCookie");
8039        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8040            return false;
8041        }
8042        synchronized (mPackages) {
8043            return mInstantAppRegistry.setInstantAppCookieLPw(
8044                    packageName, cookie, userId);
8045        }
8046    }
8047
8048    @Override
8049    public Bitmap getInstantAppIcon(String packageName, int userId) {
8050        if (HIDE_EPHEMERAL_APIS) {
8051            return null;
8052        }
8053
8054        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8055            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8056                    "getInstantAppIcon");
8057        }
8058        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8059                true /* requireFullPermission */, false /* checkShell */,
8060                "getInstantAppIcon");
8061
8062        synchronized (mPackages) {
8063            return mInstantAppRegistry.getInstantAppIconLPw(
8064                    packageName, userId);
8065        }
8066    }
8067
8068    private boolean isCallerSameApp(String packageName, int uid) {
8069        PackageParser.Package pkg = mPackages.get(packageName);
8070        return pkg != null
8071                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8072    }
8073
8074    @Override
8075    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8076        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8077            return ParceledListSlice.emptyList();
8078        }
8079        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8080    }
8081
8082    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8083        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8084
8085        // reader
8086        synchronized (mPackages) {
8087            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8088            final int userId = UserHandle.getCallingUserId();
8089            while (i.hasNext()) {
8090                final PackageParser.Package p = i.next();
8091                if (p.applicationInfo == null) continue;
8092
8093                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8094                        && !p.applicationInfo.isDirectBootAware();
8095                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8096                        && p.applicationInfo.isDirectBootAware();
8097
8098                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8099                        && (!mSafeMode || isSystemApp(p))
8100                        && (matchesUnaware || matchesAware)) {
8101                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8102                    if (ps != null) {
8103                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8104                                ps.readUserState(userId), userId);
8105                        if (ai != null) {
8106                            finalList.add(ai);
8107                        }
8108                    }
8109                }
8110            }
8111        }
8112
8113        return finalList;
8114    }
8115
8116    @Override
8117    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8118        return resolveContentProviderInternal(name, flags, userId);
8119    }
8120
8121    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8122        if (!sUserManager.exists(userId)) return null;
8123        flags = updateFlagsForComponent(flags, userId, name);
8124        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8125        // reader
8126        synchronized (mPackages) {
8127            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8128            PackageSetting ps = provider != null
8129                    ? mSettings.mPackages.get(provider.owner.packageName)
8130                    : null;
8131            if (ps != null) {
8132                final boolean isInstantApp = ps.getInstantApp(userId);
8133                // normal application; filter out instant application provider
8134                if (instantAppPkgName == null && isInstantApp) {
8135                    return null;
8136                }
8137                // instant application; filter out other instant applications
8138                if (instantAppPkgName != null
8139                        && isInstantApp
8140                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8141                    return null;
8142                }
8143                // instant application; filter out non-exposed provider
8144                if (instantAppPkgName != null
8145                        && !isInstantApp
8146                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8147                    return null;
8148                }
8149                // provider not enabled
8150                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8151                    return null;
8152                }
8153                return PackageParser.generateProviderInfo(
8154                        provider, flags, ps.readUserState(userId), userId);
8155            }
8156            return null;
8157        }
8158    }
8159
8160    /**
8161     * @deprecated
8162     */
8163    @Deprecated
8164    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8165        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8166            return;
8167        }
8168        // reader
8169        synchronized (mPackages) {
8170            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8171                    .entrySet().iterator();
8172            final int userId = UserHandle.getCallingUserId();
8173            while (i.hasNext()) {
8174                Map.Entry<String, PackageParser.Provider> entry = i.next();
8175                PackageParser.Provider p = entry.getValue();
8176                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8177
8178                if (ps != null && p.syncable
8179                        && (!mSafeMode || (p.info.applicationInfo.flags
8180                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8181                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8182                            ps.readUserState(userId), userId);
8183                    if (info != null) {
8184                        outNames.add(entry.getKey());
8185                        outInfo.add(info);
8186                    }
8187                }
8188            }
8189        }
8190    }
8191
8192    @Override
8193    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8194            int uid, int flags, String metaDataKey) {
8195        final int callingUid = Binder.getCallingUid();
8196        final int userId = processName != null ? UserHandle.getUserId(uid)
8197                : UserHandle.getCallingUserId();
8198        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8199        flags = updateFlagsForComponent(flags, userId, processName);
8200        ArrayList<ProviderInfo> finalList = null;
8201        // reader
8202        synchronized (mPackages) {
8203            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8204            while (i.hasNext()) {
8205                final PackageParser.Provider p = i.next();
8206                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8207                if (ps != null && p.info.authority != null
8208                        && (processName == null
8209                                || (p.info.processName.equals(processName)
8210                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8211                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8212
8213                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8214                    // parameter.
8215                    if (metaDataKey != null
8216                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8217                        continue;
8218                    }
8219                    final ComponentName component =
8220                            new ComponentName(p.info.packageName, p.info.name);
8221                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8222                        continue;
8223                    }
8224                    if (finalList == null) {
8225                        finalList = new ArrayList<ProviderInfo>(3);
8226                    }
8227                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8228                            ps.readUserState(userId), userId);
8229                    if (info != null) {
8230                        finalList.add(info);
8231                    }
8232                }
8233            }
8234        }
8235
8236        if (finalList != null) {
8237            Collections.sort(finalList, mProviderInitOrderSorter);
8238            return new ParceledListSlice<ProviderInfo>(finalList);
8239        }
8240
8241        return ParceledListSlice.emptyList();
8242    }
8243
8244    @Override
8245    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8246        // reader
8247        synchronized (mPackages) {
8248            final int callingUid = Binder.getCallingUid();
8249            final int callingUserId = UserHandle.getUserId(callingUid);
8250            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8251            if (ps == null) return null;
8252            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8253                return null;
8254            }
8255            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8256            return PackageParser.generateInstrumentationInfo(i, flags);
8257        }
8258    }
8259
8260    @Override
8261    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8262            String targetPackage, int flags) {
8263        final int callingUid = Binder.getCallingUid();
8264        final int callingUserId = UserHandle.getUserId(callingUid);
8265        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8266        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8267            return ParceledListSlice.emptyList();
8268        }
8269        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8270    }
8271
8272    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8273            int flags) {
8274        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8275
8276        // reader
8277        synchronized (mPackages) {
8278            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8279            while (i.hasNext()) {
8280                final PackageParser.Instrumentation p = i.next();
8281                if (targetPackage == null
8282                        || targetPackage.equals(p.info.targetPackage)) {
8283                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8284                            flags);
8285                    if (ii != null) {
8286                        finalList.add(ii);
8287                    }
8288                }
8289            }
8290        }
8291
8292        return finalList;
8293    }
8294
8295    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8296        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8297        try {
8298            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8299        } finally {
8300            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8301        }
8302    }
8303
8304    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8305        final File[] files = scanDir.listFiles();
8306        if (ArrayUtils.isEmpty(files)) {
8307            Log.d(TAG, "No files in app dir " + scanDir);
8308            return;
8309        }
8310
8311        if (DEBUG_PACKAGE_SCANNING) {
8312            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8313                    + " flags=0x" + Integer.toHexString(parseFlags));
8314        }
8315        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8316                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8317                mParallelPackageParserCallback)) {
8318            // Submit files for parsing in parallel
8319            int fileCount = 0;
8320            for (File file : files) {
8321                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8322                        && !PackageInstallerService.isStageName(file.getName());
8323                if (!isPackage) {
8324                    // Ignore entries which are not packages
8325                    continue;
8326                }
8327                parallelPackageParser.submit(file, parseFlags);
8328                fileCount++;
8329            }
8330
8331            // Process results one by one
8332            for (; fileCount > 0; fileCount--) {
8333                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8334                Throwable throwable = parseResult.throwable;
8335                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8336
8337                if (throwable == null) {
8338                    // TODO(toddke): move lower in the scan chain
8339                    // Static shared libraries have synthetic package names
8340                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8341                        renameStaticSharedLibraryPackage(parseResult.pkg);
8342                    }
8343                    try {
8344                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8345                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8346                                    currentTime, null);
8347                        }
8348                    } catch (PackageManagerException e) {
8349                        errorCode = e.error;
8350                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8351                    }
8352                } else if (throwable instanceof PackageParser.PackageParserException) {
8353                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8354                            throwable;
8355                    errorCode = e.error;
8356                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8357                } else {
8358                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8359                            + parseResult.scanFile, throwable);
8360                }
8361
8362                // Delete invalid userdata apps
8363                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8364                        errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8365                    logCriticalInfo(Log.WARN,
8366                            "Deleting invalid package at " + parseResult.scanFile);
8367                    removeCodePathLI(parseResult.scanFile);
8368                }
8369            }
8370        }
8371    }
8372
8373    public static void reportSettingsProblem(int priority, String msg) {
8374        logCriticalInfo(priority, msg);
8375    }
8376
8377    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8378            boolean forceCollect, boolean skipVerify) throws PackageManagerException {
8379        // When upgrading from pre-N MR1, verify the package time stamp using the package
8380        // directory and not the APK file.
8381        final long lastModifiedTime = mIsPreNMR1Upgrade
8382                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8383        if (ps != null && !forceCollect
8384                && ps.codePathString.equals(pkg.codePath)
8385                && ps.timeStamp == lastModifiedTime
8386                && !isCompatSignatureUpdateNeeded(pkg)
8387                && !isRecoverSignatureUpdateNeeded(pkg)) {
8388            if (ps.signatures.mSigningDetails.signatures != null
8389                    && ps.signatures.mSigningDetails.signatures.length != 0
8390                    && ps.signatures.mSigningDetails.signatureSchemeVersion
8391                            != SignatureSchemeVersion.UNKNOWN) {
8392                // Optimization: reuse the existing cached signing data
8393                // if the package appears to be unchanged.
8394                pkg.mSigningDetails =
8395                        new PackageParser.SigningDetails(ps.signatures.mSigningDetails);
8396                return;
8397            }
8398
8399            Slog.w(TAG, "PackageSetting for " + ps.name
8400                    + " is missing signatures.  Collecting certs again to recover them.");
8401        } else {
8402            Slog.i(TAG, pkg.codePath + " changed; collecting certs" +
8403                    (forceCollect ? " (forced)" : ""));
8404        }
8405
8406        try {
8407            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8408            PackageParser.collectCertificates(pkg, skipVerify);
8409        } catch (PackageParserException e) {
8410            throw PackageManagerException.from(e);
8411        } finally {
8412            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8413        }
8414    }
8415
8416    /**
8417     *  Traces a package scan.
8418     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8419     */
8420    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8421            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8422        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8423        try {
8424            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8425        } finally {
8426            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8427        }
8428    }
8429
8430    /**
8431     *  Scans a package and returns the newly parsed package.
8432     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8433     */
8434    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8435            long currentTime, UserHandle user) throws PackageManagerException {
8436        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8437        PackageParser pp = new PackageParser();
8438        pp.setSeparateProcesses(mSeparateProcesses);
8439        pp.setOnlyCoreApps(mOnlyCore);
8440        pp.setDisplayMetrics(mMetrics);
8441        pp.setCallback(mPackageParserCallback);
8442
8443        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8444        final PackageParser.Package pkg;
8445        try {
8446            pkg = pp.parsePackage(scanFile, parseFlags);
8447        } catch (PackageParserException e) {
8448            throw PackageManagerException.from(e);
8449        } finally {
8450            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8451        }
8452
8453        // Static shared libraries have synthetic package names
8454        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8455            renameStaticSharedLibraryPackage(pkg);
8456        }
8457
8458        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8459    }
8460
8461    /**
8462     *  Scans a package and returns the newly parsed package.
8463     *  @throws PackageManagerException on a parse error.
8464     */
8465    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8466            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8467            @Nullable UserHandle user)
8468                    throws PackageManagerException {
8469        // If the package has children and this is the first dive in the function
8470        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8471        // packages (parent and children) would be successfully scanned before the
8472        // actual scan since scanning mutates internal state and we want to atomically
8473        // install the package and its children.
8474        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8475            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8476                scanFlags |= SCAN_CHECK_ONLY;
8477            }
8478        } else {
8479            scanFlags &= ~SCAN_CHECK_ONLY;
8480        }
8481
8482        // Scan the parent
8483        PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags,
8484                scanFlags, currentTime, user);
8485
8486        // Scan the children
8487        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8488        for (int i = 0; i < childCount; i++) {
8489            PackageParser.Package childPackage = pkg.childPackages.get(i);
8490            addForInitLI(childPackage, parseFlags, scanFlags,
8491                    currentTime, user);
8492        }
8493
8494
8495        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8496            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8497        }
8498
8499        return scannedPkg;
8500    }
8501
8502    /**
8503     * Returns if full apk verification can be skipped for the whole package, including the splits.
8504     */
8505    private boolean canSkipFullPackageVerification(PackageParser.Package pkg) {
8506        if (!canSkipFullApkVerification(pkg.baseCodePath)) {
8507            return false;
8508        }
8509        // TODO: Allow base and splits to be verified individually.
8510        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8511            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8512                if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) {
8513                    return false;
8514                }
8515            }
8516        }
8517        return true;
8518    }
8519
8520    /**
8521     * Returns if full apk verification can be skipped, depending on current FSVerity setup and
8522     * whether the apk contains signed root hash.  Note that the signer's certificate still needs to
8523     * match one in a trusted source, and should be done separately.
8524     */
8525    private boolean canSkipFullApkVerification(String apkPath) {
8526        byte[] rootHashObserved = null;
8527        try {
8528            rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath);
8529            if (rootHashObserved == null) {
8530                return false;  // APK does not contain Merkle tree root hash.
8531            }
8532            synchronized (mInstallLock) {
8533                // Returns whether the observed root hash matches what kernel has.
8534                mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved);
8535                return true;
8536            }
8537        } catch (InstallerException | IOException | DigestException |
8538                NoSuchAlgorithmException e) {
8539            Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e);
8540        }
8541        return false;
8542    }
8543
8544    /**
8545     * Adds a new package to the internal data structures during platform initialization.
8546     * <p>After adding, the package is known to the system and available for querying.
8547     * <p>For packages located on the device ROM [eg. packages located in /system, /vendor,
8548     * etc...], additional checks are performed. Basic verification [such as ensuring
8549     * matching signatures, checking version codes, etc...] occurs if the package is
8550     * identical to a previously known package. If the package fails a signature check,
8551     * the version installed on /data will be removed. If the version of the new package
8552     * is less than or equal than the version on /data, it will be ignored.
8553     * <p>Regardless of the package location, the results are applied to the internal
8554     * structures and the package is made available to the rest of the system.
8555     * <p>NOTE: The return value should be removed. It's the passed in package object.
8556     */
8557    private PackageParser.Package addForInitLI(PackageParser.Package pkg,
8558            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8559            @Nullable UserHandle user)
8560                    throws PackageManagerException {
8561        final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0;
8562        final String renamedPkgName;
8563        final PackageSetting disabledPkgSetting;
8564        final boolean isSystemPkgUpdated;
8565        final boolean pkgAlreadyExists;
8566        PackageSetting pkgSetting;
8567
8568        // NOTE: installPackageLI() has the same code to setup the package's
8569        // application info. This probably should be done lower in the call
8570        // stack [such as scanPackageOnly()]. However, we verify the application
8571        // info prior to that [in scanPackageNew()] and thus have to setup
8572        // the application info early.
8573        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8574        pkg.setApplicationInfoCodePath(pkg.codePath);
8575        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8576        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8577        pkg.setApplicationInfoResourcePath(pkg.codePath);
8578        pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
8579        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8580
8581        synchronized (mPackages) {
8582            renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8583            final String realPkgName = getRealPackageName(pkg, renamedPkgName);
8584            if (realPkgName != null) {
8585                ensurePackageRenamed(pkg, renamedPkgName);
8586            }
8587            final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
8588            final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName);
8589            pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting;
8590            pkgAlreadyExists = pkgSetting != null;
8591            final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName;
8592            disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName);
8593            isSystemPkgUpdated = disabledPkgSetting != null;
8594
8595            if (DEBUG_INSTALL && isSystemPkgUpdated) {
8596                Slog.d(TAG, "updatedPkg = " + disabledPkgSetting);
8597            }
8598
8599            final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null)
8600                    ? mSettings.getSharedUserLPw(pkg.mSharedUserId,
8601                            0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true)
8602                    : null;
8603            if (DEBUG_PACKAGE_SCANNING
8604                    && (parseFlags & PackageParser.PARSE_CHATTY) != 0
8605                    && sharedUserSetting != null) {
8606                Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
8607                        + " (uid=" + sharedUserSetting.userId + "):"
8608                        + " packages=" + sharedUserSetting.packages);
8609            }
8610
8611            if (scanSystemPartition) {
8612                // Potentially prune child packages. If the application on the /system
8613                // partition has been updated via OTA, but, is still disabled by a
8614                // version on /data, cycle through all of its children packages and
8615                // remove children that are no longer defined.
8616                if (isSystemPkgUpdated) {
8617                    final int scannedChildCount = (pkg.childPackages != null)
8618                            ? pkg.childPackages.size() : 0;
8619                    final int disabledChildCount = disabledPkgSetting.childPackageNames != null
8620                            ? disabledPkgSetting.childPackageNames.size() : 0;
8621                    for (int i = 0; i < disabledChildCount; i++) {
8622                        String disabledChildPackageName =
8623                                disabledPkgSetting.childPackageNames.get(i);
8624                        boolean disabledPackageAvailable = false;
8625                        for (int j = 0; j < scannedChildCount; j++) {
8626                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8627                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8628                                disabledPackageAvailable = true;
8629                                break;
8630                            }
8631                        }
8632                        if (!disabledPackageAvailable) {
8633                            mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8634                        }
8635                    }
8636                    // we're updating the disabled package, so, scan it as the package setting
8637                    final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
8638                            disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */,
8639                            null /* originalPkgSetting */, null, parseFlags, scanFlags,
8640                            (pkg == mPlatformPackage), user);
8641                    scanPackageOnlyLI(request, mFactoryTest, -1L);
8642                }
8643            }
8644        }
8645
8646        final boolean newPkgChangedPaths =
8647                pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath);
8648        final boolean newPkgVersionGreater =
8649                pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode;
8650        final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated
8651                && newPkgChangedPaths && newPkgVersionGreater;
8652        if (isSystemPkgBetter) {
8653            // The version of the application on /system is greater than the version on
8654            // /data. Switch back to the application on /system.
8655            // It's safe to assume the application on /system will correctly scan. If not,
8656            // there won't be a working copy of the application.
8657            synchronized (mPackages) {
8658                // just remove the loaded entries from package lists
8659                mPackages.remove(pkgSetting.name);
8660            }
8661
8662            logCriticalInfo(Log.WARN,
8663                    "System package updated;"
8664                    + " name: " + pkgSetting.name
8665                    + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8666                    + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8667
8668            final InstallArgs args = createInstallArgsForExisting(
8669                    packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8670                    pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8671            args.cleanUpResourcesLI();
8672            synchronized (mPackages) {
8673                mSettings.enableSystemPackageLPw(pkgSetting.name);
8674            }
8675        }
8676
8677        if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) {
8678            // The version of the application on the /system partition is less than or
8679            // equal to the version on the /data partition. Throw an exception and use
8680            // the application already installed on the /data partition.
8681            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8682                    + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode
8683                    + " better than this " + pkg.getLongVersionCode());
8684        }
8685
8686        // Verify certificates against what was last scanned. If it is an updated priv app, we will
8687        // force re-collecting certificate.
8688        final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced(
8689                disabledPkgSetting);
8690        // Full APK verification can be skipped during certificate collection, only if the file is
8691        // in verified partition, or can be verified on access (when apk verity is enabled). In both
8692        // cases, only data in Signing Block is verified instead of the whole file.
8693        final boolean skipVerify = ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) ||
8694                (forceCollect && canSkipFullPackageVerification(pkg));
8695        collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify);
8696
8697        boolean shouldHideSystemApp = false;
8698        // A new application appeared on /system, but, we already have a copy of
8699        // the application installed on /data.
8700        if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists
8701                && !pkgSetting.isSystem()) {
8702
8703            if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails,
8704                    PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
8705                logCriticalInfo(Log.WARN,
8706                        "System package signature mismatch;"
8707                        + " name: " + pkgSetting.name);
8708                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8709                        "scanPackageInternalLI")) {
8710                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8711                }
8712                pkgSetting = null;
8713            } else if (newPkgVersionGreater) {
8714                // The application on /system is newer than the application on /data.
8715                // Simply remove the application on /data [keeping application data]
8716                // and replace it with the version on /system.
8717                logCriticalInfo(Log.WARN,
8718                        "System package enabled;"
8719                        + " name: " + pkgSetting.name
8720                        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8721                        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8722                InstallArgs args = createInstallArgsForExisting(
8723                        packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8724                        pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8725                synchronized (mInstallLock) {
8726                    args.cleanUpResourcesLI();
8727                }
8728            } else {
8729                // The application on /system is older than the application on /data. Hide
8730                // the application on /system and the version on /data will be scanned later
8731                // and re-added like an update.
8732                shouldHideSystemApp = true;
8733                logCriticalInfo(Log.INFO,
8734                        "System package disabled;"
8735                        + " name: " + pkgSetting.name
8736                        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8737                        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8738            }
8739        }
8740
8741        final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8742                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8743
8744        if (shouldHideSystemApp) {
8745            synchronized (mPackages) {
8746                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8747            }
8748        }
8749        return scannedPkg;
8750    }
8751
8752    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8753        // Derive the new package synthetic package name
8754        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8755                + pkg.staticSharedLibVersion);
8756    }
8757
8758    private static String fixProcessName(String defProcessName,
8759            String processName) {
8760        if (processName == null) {
8761            return defProcessName;
8762        }
8763        return processName;
8764    }
8765
8766    /**
8767     * Enforces that only the system UID or root's UID can call a method exposed
8768     * via Binder.
8769     *
8770     * @param message used as message if SecurityException is thrown
8771     * @throws SecurityException if the caller is not system or root
8772     */
8773    private static final void enforceSystemOrRoot(String message) {
8774        final int uid = Binder.getCallingUid();
8775        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8776            throw new SecurityException(message);
8777        }
8778    }
8779
8780    @Override
8781    public void performFstrimIfNeeded() {
8782        enforceSystemOrRoot("Only the system can request fstrim");
8783
8784        // Before everything else, see whether we need to fstrim.
8785        try {
8786            IStorageManager sm = PackageHelper.getStorageManager();
8787            if (sm != null) {
8788                boolean doTrim = false;
8789                final long interval = android.provider.Settings.Global.getLong(
8790                        mContext.getContentResolver(),
8791                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8792                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8793                if (interval > 0) {
8794                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8795                    if (timeSinceLast > interval) {
8796                        doTrim = true;
8797                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8798                                + "; running immediately");
8799                    }
8800                }
8801                if (doTrim) {
8802                    final boolean dexOptDialogShown;
8803                    synchronized (mPackages) {
8804                        dexOptDialogShown = mDexOptDialogShown;
8805                    }
8806                    if (!isFirstBoot() && dexOptDialogShown) {
8807                        try {
8808                            ActivityManager.getService().showBootMessage(
8809                                    mContext.getResources().getString(
8810                                            R.string.android_upgrading_fstrim), true);
8811                        } catch (RemoteException e) {
8812                        }
8813                    }
8814                    sm.runMaintenance();
8815                }
8816            } else {
8817                Slog.e(TAG, "storageManager service unavailable!");
8818            }
8819        } catch (RemoteException e) {
8820            // Can't happen; StorageManagerService is local
8821        }
8822    }
8823
8824    @Override
8825    public void updatePackagesIfNeeded() {
8826        enforceSystemOrRoot("Only the system can request package update");
8827
8828        // We need to re-extract after an OTA.
8829        boolean causeUpgrade = isUpgrade();
8830
8831        // First boot or factory reset.
8832        // Note: we also handle devices that are upgrading to N right now as if it is their
8833        //       first boot, as they do not have profile data.
8834        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8835
8836        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8837        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8838
8839        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8840            return;
8841        }
8842
8843        List<PackageParser.Package> pkgs;
8844        synchronized (mPackages) {
8845            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8846        }
8847
8848        final long startTime = System.nanoTime();
8849        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8850                    causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
8851                    false /* bootComplete */);
8852
8853        final int elapsedTimeSeconds =
8854                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8855
8856        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8857        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8858        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8859        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8860        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8861    }
8862
8863    /*
8864     * Return the prebuilt profile path given a package base code path.
8865     */
8866    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8867        return pkg.baseCodePath + ".prof";
8868    }
8869
8870    /**
8871     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8872     * containing statistics about the invocation. The array consists of three elements,
8873     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8874     * and {@code numberOfPackagesFailed}.
8875     */
8876    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8877            final int compilationReason, boolean bootComplete) {
8878
8879        int numberOfPackagesVisited = 0;
8880        int numberOfPackagesOptimized = 0;
8881        int numberOfPackagesSkipped = 0;
8882        int numberOfPackagesFailed = 0;
8883        final int numberOfPackagesToDexopt = pkgs.size();
8884
8885        for (PackageParser.Package pkg : pkgs) {
8886            numberOfPackagesVisited++;
8887
8888            boolean useProfileForDexopt = false;
8889
8890            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8891                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8892                // that are already compiled.
8893                File profileFile = new File(getPrebuildProfilePath(pkg));
8894                // Copy profile if it exists.
8895                if (profileFile.exists()) {
8896                    try {
8897                        // We could also do this lazily before calling dexopt in
8898                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8899                        // is that we don't have a good way to say "do this only once".
8900                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8901                                pkg.applicationInfo.uid, pkg.packageName,
8902                                ArtManager.getProfileName(null))) {
8903                            Log.e(TAG, "Installer failed to copy system profile!");
8904                        } else {
8905                            // Disabled as this causes speed-profile compilation during first boot
8906                            // even if things are already compiled.
8907                            // useProfileForDexopt = true;
8908                        }
8909                    } catch (Exception e) {
8910                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
8911                                e);
8912                    }
8913                } else {
8914                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8915                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
8916                    // minimize the number off apps being speed-profile compiled during first boot.
8917                    // The other paths will not change the filter.
8918                    if (disabledPs != null && disabledPs.pkg.isStub) {
8919                        // The package is the stub one, remove the stub suffix to get the normal
8920                        // package and APK names.
8921                        String systemProfilePath =
8922                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
8923                        profileFile = new File(systemProfilePath);
8924                        // If we have a profile for a compressed APK, copy it to the reference
8925                        // location.
8926                        // Note that copying the profile here will cause it to override the
8927                        // reference profile every OTA even though the existing reference profile
8928                        // may have more data. We can't copy during decompression since the
8929                        // directories are not set up at that point.
8930                        if (profileFile.exists()) {
8931                            try {
8932                                // We could also do this lazily before calling dexopt in
8933                                // PackageDexOptimizer to prevent this happening on first boot. The
8934                                // issue is that we don't have a good way to say "do this only
8935                                // once".
8936                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8937                                        pkg.applicationInfo.uid, pkg.packageName,
8938                                        ArtManager.getProfileName(null))) {
8939                                    Log.e(TAG, "Failed to copy system profile for stub package!");
8940                                } else {
8941                                    useProfileForDexopt = true;
8942                                }
8943                            } catch (Exception e) {
8944                                Log.e(TAG, "Failed to copy profile " +
8945                                        profileFile.getAbsolutePath() + " ", e);
8946                            }
8947                        }
8948                    }
8949                }
8950            }
8951
8952            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8953                if (DEBUG_DEXOPT) {
8954                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8955                }
8956                numberOfPackagesSkipped++;
8957                continue;
8958            }
8959
8960            if (DEBUG_DEXOPT) {
8961                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8962                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8963            }
8964
8965            if (showDialog) {
8966                try {
8967                    ActivityManager.getService().showBootMessage(
8968                            mContext.getResources().getString(R.string.android_upgrading_apk,
8969                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8970                } catch (RemoteException e) {
8971                }
8972                synchronized (mPackages) {
8973                    mDexOptDialogShown = true;
8974                }
8975            }
8976
8977            int pkgCompilationReason = compilationReason;
8978            if (useProfileForDexopt) {
8979                // Use background dexopt mode to try and use the profile. Note that this does not
8980                // guarantee usage of the profile.
8981                pkgCompilationReason = PackageManagerService.REASON_BACKGROUND_DEXOPT;
8982            }
8983
8984            // checkProfiles is false to avoid merging profiles during boot which
8985            // might interfere with background compilation (b/28612421).
8986            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8987            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8988            // trade-off worth doing to save boot time work.
8989            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
8990            if (compilationReason == REASON_FIRST_BOOT) {
8991                // TODO: This doesn't cover the upgrade case, we should check for this too.
8992                dexoptFlags |= DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE;
8993            }
8994            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
8995                    pkg.packageName,
8996                    pkgCompilationReason,
8997                    dexoptFlags));
8998
8999            switch (primaryDexOptStaus) {
9000                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9001                    numberOfPackagesOptimized++;
9002                    break;
9003                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9004                    numberOfPackagesSkipped++;
9005                    break;
9006                case PackageDexOptimizer.DEX_OPT_FAILED:
9007                    numberOfPackagesFailed++;
9008                    break;
9009                default:
9010                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9011                    break;
9012            }
9013        }
9014
9015        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9016                numberOfPackagesFailed };
9017    }
9018
9019    @Override
9020    public void notifyPackageUse(String packageName, int reason) {
9021        synchronized (mPackages) {
9022            final int callingUid = Binder.getCallingUid();
9023            final int callingUserId = UserHandle.getUserId(callingUid);
9024            if (getInstantAppPackageName(callingUid) != null) {
9025                if (!isCallerSameApp(packageName, callingUid)) {
9026                    return;
9027                }
9028            } else {
9029                if (isInstantApp(packageName, callingUserId)) {
9030                    return;
9031                }
9032            }
9033            notifyPackageUseLocked(packageName, reason);
9034        }
9035    }
9036
9037    @GuardedBy("mPackages")
9038    private void notifyPackageUseLocked(String packageName, int reason) {
9039        final PackageParser.Package p = mPackages.get(packageName);
9040        if (p == null) {
9041            return;
9042        }
9043        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9044    }
9045
9046    @Override
9047    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9048            List<String> classPaths, String loaderIsa) {
9049        int userId = UserHandle.getCallingUserId();
9050        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9051        if (ai == null) {
9052            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9053                + loadingPackageName + ", user=" + userId);
9054            return;
9055        }
9056        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9057    }
9058
9059    @Override
9060    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9061            IDexModuleRegisterCallback callback) {
9062        int userId = UserHandle.getCallingUserId();
9063        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9064        DexManager.RegisterDexModuleResult result;
9065        if (ai == null) {
9066            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9067                     " calling user. package=" + packageName + ", user=" + userId);
9068            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9069        } else {
9070            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9071        }
9072
9073        if (callback != null) {
9074            mHandler.post(() -> {
9075                try {
9076                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9077                } catch (RemoteException e) {
9078                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9079                }
9080            });
9081        }
9082    }
9083
9084    /**
9085     * Ask the package manager to perform a dex-opt with the given compiler filter.
9086     *
9087     * Note: exposed only for the shell command to allow moving packages explicitly to a
9088     *       definite state.
9089     */
9090    @Override
9091    public boolean performDexOptMode(String packageName,
9092            boolean checkProfiles, String targetCompilerFilter, boolean force,
9093            boolean bootComplete, String splitName) {
9094        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9095                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9096                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9097        return performDexOpt(new DexoptOptions(packageName, REASON_UNKNOWN,
9098                targetCompilerFilter, splitName, flags));
9099    }
9100
9101    /**
9102     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9103     * secondary dex files belonging to the given package.
9104     *
9105     * Note: exposed only for the shell command to allow moving packages explicitly to a
9106     *       definite state.
9107     */
9108    @Override
9109    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9110            boolean force) {
9111        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9112                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9113                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9114                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9115        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9116    }
9117
9118    /*package*/ boolean performDexOpt(DexoptOptions options) {
9119        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9120            return false;
9121        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9122            return false;
9123        }
9124
9125        if (options.isDexoptOnlySecondaryDex()) {
9126            return mDexManager.dexoptSecondaryDex(options);
9127        } else {
9128            int dexoptStatus = performDexOptWithStatus(options);
9129            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9130        }
9131    }
9132
9133    /**
9134     * Perform dexopt on the given package and return one of following result:
9135     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9136     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9137     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9138     */
9139    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9140        return performDexOptTraced(options);
9141    }
9142
9143    private int performDexOptTraced(DexoptOptions options) {
9144        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9145        try {
9146            return performDexOptInternal(options);
9147        } finally {
9148            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9149        }
9150    }
9151
9152    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9153    // if the package can now be considered up to date for the given filter.
9154    private int performDexOptInternal(DexoptOptions options) {
9155        PackageParser.Package p;
9156        synchronized (mPackages) {
9157            p = mPackages.get(options.getPackageName());
9158            if (p == null) {
9159                // Package could not be found. Report failure.
9160                return PackageDexOptimizer.DEX_OPT_FAILED;
9161            }
9162            mPackageUsage.maybeWriteAsync(mPackages);
9163            mCompilerStats.maybeWriteAsync();
9164        }
9165        long callingId = Binder.clearCallingIdentity();
9166        try {
9167            synchronized (mInstallLock) {
9168                return performDexOptInternalWithDependenciesLI(p, options);
9169            }
9170        } finally {
9171            Binder.restoreCallingIdentity(callingId);
9172        }
9173    }
9174
9175    public ArraySet<String> getOptimizablePackages() {
9176        ArraySet<String> pkgs = new ArraySet<String>();
9177        synchronized (mPackages) {
9178            for (PackageParser.Package p : mPackages.values()) {
9179                if (PackageDexOptimizer.canOptimizePackage(p)) {
9180                    pkgs.add(p.packageName);
9181                }
9182            }
9183        }
9184        return pkgs;
9185    }
9186
9187    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9188            DexoptOptions options) {
9189        // Select the dex optimizer based on the force parameter.
9190        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9191        //       allocate an object here.
9192        PackageDexOptimizer pdo = options.isForce()
9193                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9194                : mPackageDexOptimizer;
9195
9196        // Dexopt all dependencies first. Note: we ignore the return value and march on
9197        // on errors.
9198        // Note that we are going to call performDexOpt on those libraries as many times as
9199        // they are referenced in packages. When we do a batch of performDexOpt (for example
9200        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9201        // and the first package that uses the library will dexopt it. The
9202        // others will see that the compiled code for the library is up to date.
9203        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9204        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9205        if (!deps.isEmpty()) {
9206            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9207                    options.getCompilationReason(), options.getCompilerFilter(),
9208                    options.getSplitName(),
9209                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9210            for (PackageParser.Package depPackage : deps) {
9211                // TODO: Analyze and investigate if we (should) profile libraries.
9212                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9213                        getOrCreateCompilerPackageStats(depPackage),
9214                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9215            }
9216        }
9217        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9218                getOrCreateCompilerPackageStats(p),
9219                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9220    }
9221
9222    /**
9223     * Reconcile the information we have about the secondary dex files belonging to
9224     * {@code packagName} and the actual dex files. For all dex files that were
9225     * deleted, update the internal records and delete the generated oat files.
9226     */
9227    @Override
9228    public void reconcileSecondaryDexFiles(String packageName) {
9229        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9230            return;
9231        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9232            return;
9233        }
9234        mDexManager.reconcileSecondaryDexFiles(packageName);
9235    }
9236
9237    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9238    // a reference there.
9239    /*package*/ DexManager getDexManager() {
9240        return mDexManager;
9241    }
9242
9243    /**
9244     * Execute the background dexopt job immediately.
9245     */
9246    @Override
9247    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9248        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9249            return false;
9250        }
9251        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9252    }
9253
9254    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9255        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9256                || p.usesStaticLibraries != null) {
9257            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9258            Set<String> collectedNames = new HashSet<>();
9259            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9260
9261            retValue.remove(p);
9262
9263            return retValue;
9264        } else {
9265            return Collections.emptyList();
9266        }
9267    }
9268
9269    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9270            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9271        if (!collectedNames.contains(p.packageName)) {
9272            collectedNames.add(p.packageName);
9273            collected.add(p);
9274
9275            if (p.usesLibraries != null) {
9276                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9277                        null, collected, collectedNames);
9278            }
9279            if (p.usesOptionalLibraries != null) {
9280                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9281                        null, collected, collectedNames);
9282            }
9283            if (p.usesStaticLibraries != null) {
9284                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9285                        p.usesStaticLibrariesVersions, collected, collectedNames);
9286            }
9287        }
9288    }
9289
9290    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9291            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9292        final int libNameCount = libs.size();
9293        for (int i = 0; i < libNameCount; i++) {
9294            String libName = libs.get(i);
9295            long version = (versions != null && versions.length == libNameCount)
9296                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9297            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9298            if (libPkg != null) {
9299                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9300            }
9301        }
9302    }
9303
9304    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9305        synchronized (mPackages) {
9306            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9307            if (libEntry != null) {
9308                return mPackages.get(libEntry.apk);
9309            }
9310            return null;
9311        }
9312    }
9313
9314    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9315        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9316        if (versionedLib == null) {
9317            return null;
9318        }
9319        return versionedLib.get(version);
9320    }
9321
9322    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9323        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9324                pkg.staticSharedLibName);
9325        if (versionedLib == null) {
9326            return null;
9327        }
9328        long previousLibVersion = -1;
9329        final int versionCount = versionedLib.size();
9330        for (int i = 0; i < versionCount; i++) {
9331            final long libVersion = versionedLib.keyAt(i);
9332            if (libVersion < pkg.staticSharedLibVersion) {
9333                previousLibVersion = Math.max(previousLibVersion, libVersion);
9334            }
9335        }
9336        if (previousLibVersion >= 0) {
9337            return versionedLib.get(previousLibVersion);
9338        }
9339        return null;
9340    }
9341
9342    public void shutdown() {
9343        mPackageUsage.writeNow(mPackages);
9344        mCompilerStats.writeNow();
9345        mDexManager.writePackageDexUsageNow();
9346    }
9347
9348    @Override
9349    public void dumpProfiles(String packageName) {
9350        PackageParser.Package pkg;
9351        synchronized (mPackages) {
9352            pkg = mPackages.get(packageName);
9353            if (pkg == null) {
9354                throw new IllegalArgumentException("Unknown package: " + packageName);
9355            }
9356        }
9357        /* Only the shell, root, or the app user should be able to dump profiles. */
9358        int callingUid = Binder.getCallingUid();
9359        if (callingUid != Process.SHELL_UID &&
9360            callingUid != Process.ROOT_UID &&
9361            callingUid != pkg.applicationInfo.uid) {
9362            throw new SecurityException("dumpProfiles");
9363        }
9364
9365        synchronized (mInstallLock) {
9366            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9367            mArtManagerService.dumpProfiles(pkg);
9368            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9369        }
9370    }
9371
9372    @Override
9373    public void forceDexOpt(String packageName) {
9374        enforceSystemOrRoot("forceDexOpt");
9375
9376        PackageParser.Package pkg;
9377        synchronized (mPackages) {
9378            pkg = mPackages.get(packageName);
9379            if (pkg == null) {
9380                throw new IllegalArgumentException("Unknown package: " + packageName);
9381            }
9382        }
9383
9384        synchronized (mInstallLock) {
9385            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9386
9387            // Whoever is calling forceDexOpt wants a compiled package.
9388            // Don't use profiles since that may cause compilation to be skipped.
9389            final int res = performDexOptInternalWithDependenciesLI(
9390                    pkg,
9391                    new DexoptOptions(packageName,
9392                            getDefaultCompilerFilter(),
9393                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9394
9395            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9396            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9397                throw new IllegalStateException("Failed to dexopt: " + res);
9398            }
9399        }
9400    }
9401
9402    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9403        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9404            Slog.w(TAG, "Unable to update from " + oldPkg.name
9405                    + " to " + newPkg.packageName
9406                    + ": old package not in system partition");
9407            return false;
9408        } else if (mPackages.get(oldPkg.name) != null) {
9409            Slog.w(TAG, "Unable to update from " + oldPkg.name
9410                    + " to " + newPkg.packageName
9411                    + ": old package still exists");
9412            return false;
9413        }
9414        return true;
9415    }
9416
9417    void removeCodePathLI(File codePath) {
9418        if (codePath.isDirectory()) {
9419            try {
9420                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9421            } catch (InstallerException e) {
9422                Slog.w(TAG, "Failed to remove code path", e);
9423            }
9424        } else {
9425            codePath.delete();
9426        }
9427    }
9428
9429    private int[] resolveUserIds(int userId) {
9430        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9431    }
9432
9433    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9434        if (pkg == null) {
9435            Slog.wtf(TAG, "Package was null!", new Throwable());
9436            return;
9437        }
9438        clearAppDataLeafLIF(pkg, userId, flags);
9439        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9440        for (int i = 0; i < childCount; i++) {
9441            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9442        }
9443
9444        clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
9445    }
9446
9447    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9448        final PackageSetting ps;
9449        synchronized (mPackages) {
9450            ps = mSettings.mPackages.get(pkg.packageName);
9451        }
9452        for (int realUserId : resolveUserIds(userId)) {
9453            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9454            try {
9455                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9456                        ceDataInode);
9457            } catch (InstallerException e) {
9458                Slog.w(TAG, String.valueOf(e));
9459            }
9460        }
9461    }
9462
9463    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9464        if (pkg == null) {
9465            Slog.wtf(TAG, "Package was null!", new Throwable());
9466            return;
9467        }
9468        destroyAppDataLeafLIF(pkg, userId, flags);
9469        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9470        for (int i = 0; i < childCount; i++) {
9471            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9472        }
9473    }
9474
9475    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9476        final PackageSetting ps;
9477        synchronized (mPackages) {
9478            ps = mSettings.mPackages.get(pkg.packageName);
9479        }
9480        for (int realUserId : resolveUserIds(userId)) {
9481            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9482            try {
9483                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9484                        ceDataInode);
9485            } catch (InstallerException e) {
9486                Slog.w(TAG, String.valueOf(e));
9487            }
9488            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9489        }
9490    }
9491
9492    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9493        if (pkg == null) {
9494            Slog.wtf(TAG, "Package was null!", new Throwable());
9495            return;
9496        }
9497        destroyAppProfilesLeafLIF(pkg);
9498        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9499        for (int i = 0; i < childCount; i++) {
9500            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9501        }
9502    }
9503
9504    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9505        try {
9506            mInstaller.destroyAppProfiles(pkg.packageName);
9507        } catch (InstallerException e) {
9508            Slog.w(TAG, String.valueOf(e));
9509        }
9510    }
9511
9512    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9513        if (pkg == null) {
9514            Slog.wtf(TAG, "Package was null!", new Throwable());
9515            return;
9516        }
9517        mArtManagerService.clearAppProfiles(pkg);
9518        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9519        for (int i = 0; i < childCount; i++) {
9520            mArtManagerService.clearAppProfiles(pkg.childPackages.get(i));
9521        }
9522    }
9523
9524    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9525            long lastUpdateTime) {
9526        // Set parent install/update time
9527        PackageSetting ps = (PackageSetting) pkg.mExtras;
9528        if (ps != null) {
9529            ps.firstInstallTime = firstInstallTime;
9530            ps.lastUpdateTime = lastUpdateTime;
9531        }
9532        // Set children install/update time
9533        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9534        for (int i = 0; i < childCount; i++) {
9535            PackageParser.Package childPkg = pkg.childPackages.get(i);
9536            ps = (PackageSetting) childPkg.mExtras;
9537            if (ps != null) {
9538                ps.firstInstallTime = firstInstallTime;
9539                ps.lastUpdateTime = lastUpdateTime;
9540            }
9541        }
9542    }
9543
9544    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9545            SharedLibraryEntry file,
9546            PackageParser.Package changingLib) {
9547        if (file.path != null) {
9548            usesLibraryFiles.add(file.path);
9549            return;
9550        }
9551        PackageParser.Package p = mPackages.get(file.apk);
9552        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9553            // If we are doing this while in the middle of updating a library apk,
9554            // then we need to make sure to use that new apk for determining the
9555            // dependencies here.  (We haven't yet finished committing the new apk
9556            // to the package manager state.)
9557            if (p == null || p.packageName.equals(changingLib.packageName)) {
9558                p = changingLib;
9559            }
9560        }
9561        if (p != null) {
9562            usesLibraryFiles.addAll(p.getAllCodePaths());
9563            if (p.usesLibraryFiles != null) {
9564                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9565            }
9566        }
9567    }
9568
9569    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9570            PackageParser.Package changingLib) throws PackageManagerException {
9571        if (pkg == null) {
9572            return;
9573        }
9574        // The collection used here must maintain the order of addition (so
9575        // that libraries are searched in the correct order) and must have no
9576        // duplicates.
9577        Set<String> usesLibraryFiles = null;
9578        if (pkg.usesLibraries != null) {
9579            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9580                    null, null, pkg.packageName, changingLib, true,
9581                    pkg.applicationInfo.targetSdkVersion, null);
9582        }
9583        if (pkg.usesStaticLibraries != null) {
9584            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9585                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9586                    pkg.packageName, changingLib, true,
9587                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9588        }
9589        if (pkg.usesOptionalLibraries != null) {
9590            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9591                    null, null, pkg.packageName, changingLib, false,
9592                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9593        }
9594        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9595            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9596        } else {
9597            pkg.usesLibraryFiles = null;
9598        }
9599    }
9600
9601    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9602            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9603            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9604            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9605            throws PackageManagerException {
9606        final int libCount = requestedLibraries.size();
9607        for (int i = 0; i < libCount; i++) {
9608            final String libName = requestedLibraries.get(i);
9609            final long libVersion = requiredVersions != null ? requiredVersions[i]
9610                    : SharedLibraryInfo.VERSION_UNDEFINED;
9611            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9612            if (libEntry == null) {
9613                if (required) {
9614                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9615                            "Package " + packageName + " requires unavailable shared library "
9616                                    + libName + "; failing!");
9617                } else if (DEBUG_SHARED_LIBRARIES) {
9618                    Slog.i(TAG, "Package " + packageName
9619                            + " desires unavailable shared library "
9620                            + libName + "; ignoring!");
9621                }
9622            } else {
9623                if (requiredVersions != null && requiredCertDigests != null) {
9624                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9625                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9626                            "Package " + packageName + " requires unavailable static shared"
9627                                    + " library " + libName + " version "
9628                                    + libEntry.info.getLongVersion() + "; failing!");
9629                    }
9630
9631                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9632                    if (libPkg == null) {
9633                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9634                                "Package " + packageName + " requires unavailable static shared"
9635                                        + " library; failing!");
9636                    }
9637
9638                    final String[] expectedCertDigests = requiredCertDigests[i];
9639
9640
9641                    if (expectedCertDigests.length > 1) {
9642
9643                        // For apps targeting O MR1 we require explicit enumeration of all certs.
9644                        final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9645                                ? PackageUtils.computeSignaturesSha256Digests(
9646                                libPkg.mSigningDetails.signatures)
9647                                : PackageUtils.computeSignaturesSha256Digests(
9648                                        new Signature[]{libPkg.mSigningDetails.signatures[0]});
9649
9650                        // Take a shortcut if sizes don't match. Note that if an app doesn't
9651                        // target O we don't parse the "additional-certificate" tags similarly
9652                        // how we only consider all certs only for apps targeting O (see above).
9653                        // Therefore, the size check is safe to make.
9654                        if (expectedCertDigests.length != libCertDigests.length) {
9655                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9656                                    "Package " + packageName + " requires differently signed" +
9657                                            " static shared library; failing!");
9658                        }
9659
9660                        // Use a predictable order as signature order may vary
9661                        Arrays.sort(libCertDigests);
9662                        Arrays.sort(expectedCertDigests);
9663
9664                        final int certCount = libCertDigests.length;
9665                        for (int j = 0; j < certCount; j++) {
9666                            if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9667                                throw new PackageManagerException(
9668                                        INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9669                                        "Package " + packageName + " requires differently signed" +
9670                                                " static shared library; failing!");
9671                            }
9672                        }
9673                    } else {
9674
9675                        // lib signing cert could have rotated beyond the one expected, check to see
9676                        // if the new one has been blessed by the old
9677                        if (!libPkg.mSigningDetails.hasSha256Certificate(
9678                                ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) {
9679                            throw new PackageManagerException(
9680                                    INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9681                                    "Package " + packageName + " requires differently signed" +
9682                                            " static shared library; failing!");
9683                        }
9684                    }
9685                }
9686
9687                if (outUsedLibraries == null) {
9688                    // Use LinkedHashSet to preserve the order of files added to
9689                    // usesLibraryFiles while eliminating duplicates.
9690                    outUsedLibraries = new LinkedHashSet<>();
9691                }
9692                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9693            }
9694        }
9695        return outUsedLibraries;
9696    }
9697
9698    private static boolean hasString(List<String> list, List<String> which) {
9699        if (list == null) {
9700            return false;
9701        }
9702        for (int i=list.size()-1; i>=0; i--) {
9703            for (int j=which.size()-1; j>=0; j--) {
9704                if (which.get(j).equals(list.get(i))) {
9705                    return true;
9706                }
9707            }
9708        }
9709        return false;
9710    }
9711
9712    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9713            PackageParser.Package changingPkg) {
9714        ArrayList<PackageParser.Package> res = null;
9715        for (PackageParser.Package pkg : mPackages.values()) {
9716            if (changingPkg != null
9717                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9718                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9719                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9720                            changingPkg.staticSharedLibName)) {
9721                return null;
9722            }
9723            if (res == null) {
9724                res = new ArrayList<>();
9725            }
9726            res.add(pkg);
9727            try {
9728                updateSharedLibrariesLPr(pkg, changingPkg);
9729            } catch (PackageManagerException e) {
9730                // If a system app update or an app and a required lib missing we
9731                // delete the package and for updated system apps keep the data as
9732                // it is better for the user to reinstall than to be in an limbo
9733                // state. Also libs disappearing under an app should never happen
9734                // - just in case.
9735                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9736                    final int flags = pkg.isUpdatedSystemApp()
9737                            ? PackageManager.DELETE_KEEP_DATA : 0;
9738                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9739                            flags , null, true, null);
9740                }
9741                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9742            }
9743        }
9744        return res;
9745    }
9746
9747    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9748            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9749            @Nullable UserHandle user) throws PackageManagerException {
9750        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9751        // If the package has children and this is the first dive in the function
9752        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9753        // whether all packages (parent and children) would be successfully scanned
9754        // before the actual scan since scanning mutates internal state and we want
9755        // to atomically install the package and its children.
9756        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9757            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9758                scanFlags |= SCAN_CHECK_ONLY;
9759            }
9760        } else {
9761            scanFlags &= ~SCAN_CHECK_ONLY;
9762        }
9763
9764        final PackageParser.Package scannedPkg;
9765        try {
9766            // Scan the parent
9767            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9768            // Scan the children
9769            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9770            for (int i = 0; i < childCount; i++) {
9771                PackageParser.Package childPkg = pkg.childPackages.get(i);
9772                scanPackageNewLI(childPkg, parseFlags,
9773                        scanFlags, currentTime, user);
9774            }
9775        } finally {
9776            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9777        }
9778
9779        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9780            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9781        }
9782
9783        return scannedPkg;
9784    }
9785
9786    /** The result of a package scan. */
9787    private static class ScanResult {
9788        /** Whether or not the package scan was successful */
9789        public final boolean success;
9790        /**
9791         * The final package settings. This may be the same object passed in
9792         * the {@link ScanRequest}, but, with modified values.
9793         */
9794        @Nullable public final PackageSetting pkgSetting;
9795        /** ABI code paths that have changed in the package scan */
9796        @Nullable public final List<String> changedAbiCodePath;
9797        public ScanResult(
9798                boolean success,
9799                @Nullable PackageSetting pkgSetting,
9800                @Nullable List<String> changedAbiCodePath) {
9801            this.success = success;
9802            this.pkgSetting = pkgSetting;
9803            this.changedAbiCodePath = changedAbiCodePath;
9804        }
9805    }
9806
9807    /** A package to be scanned */
9808    private static class ScanRequest {
9809        /** The parsed package */
9810        @NonNull public final PackageParser.Package pkg;
9811        /** Shared user settings, if the package has a shared user */
9812        @Nullable public final SharedUserSetting sharedUserSetting;
9813        /**
9814         * Package settings of the currently installed version.
9815         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9816         * during scan.
9817         */
9818        @Nullable public final PackageSetting pkgSetting;
9819        /** A copy of the settings for the currently installed version */
9820        @Nullable public final PackageSetting oldPkgSetting;
9821        /** Package settings for the disabled version on the /system partition */
9822        @Nullable public final PackageSetting disabledPkgSetting;
9823        /** Package settings for the installed version under its original package name */
9824        @Nullable public final PackageSetting originalPkgSetting;
9825        /** The real package name of a renamed application */
9826        @Nullable public final String realPkgName;
9827        public final @ParseFlags int parseFlags;
9828        public final @ScanFlags int scanFlags;
9829        /** The user for which the package is being scanned */
9830        @Nullable public final UserHandle user;
9831        /** Whether or not the platform package is being scanned */
9832        public final boolean isPlatformPackage;
9833        public ScanRequest(
9834                @NonNull PackageParser.Package pkg,
9835                @Nullable SharedUserSetting sharedUserSetting,
9836                @Nullable PackageSetting pkgSetting,
9837                @Nullable PackageSetting disabledPkgSetting,
9838                @Nullable PackageSetting originalPkgSetting,
9839                @Nullable String realPkgName,
9840                @ParseFlags int parseFlags,
9841                @ScanFlags int scanFlags,
9842                boolean isPlatformPackage,
9843                @Nullable UserHandle user) {
9844            this.pkg = pkg;
9845            this.pkgSetting = pkgSetting;
9846            this.sharedUserSetting = sharedUserSetting;
9847            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9848            this.disabledPkgSetting = disabledPkgSetting;
9849            this.originalPkgSetting = originalPkgSetting;
9850            this.realPkgName = realPkgName;
9851            this.parseFlags = parseFlags;
9852            this.scanFlags = scanFlags;
9853            this.isPlatformPackage = isPlatformPackage;
9854            this.user = user;
9855        }
9856    }
9857
9858    /**
9859     * Returns the actual scan flags depending upon the state of the other settings.
9860     * <p>Updated system applications will not have the following flags set
9861     * by default and need to be adjusted after the fact:
9862     * <ul>
9863     * <li>{@link #SCAN_AS_SYSTEM}</li>
9864     * <li>{@link #SCAN_AS_PRIVILEGED}</li>
9865     * <li>{@link #SCAN_AS_OEM}</li>
9866     * <li>{@link #SCAN_AS_VENDOR}</li>
9867     * <li>{@link #SCAN_AS_PRODUCT}</li>
9868     * <li>{@link #SCAN_AS_INSTANT_APP}</li>
9869     * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li>
9870     * </ul>
9871     */
9872    private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags,
9873            PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user,
9874            PackageParser.Package pkg) {
9875        if (disabledPkgSetting != null) {
9876            // updated system application, must at least have SCAN_AS_SYSTEM
9877            scanFlags |= SCAN_AS_SYSTEM;
9878            if ((disabledPkgSetting.pkgPrivateFlags
9879                    & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9880                scanFlags |= SCAN_AS_PRIVILEGED;
9881            }
9882            if ((disabledPkgSetting.pkgPrivateFlags
9883                    & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
9884                scanFlags |= SCAN_AS_OEM;
9885            }
9886            if ((disabledPkgSetting.pkgPrivateFlags
9887                    & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
9888                scanFlags |= SCAN_AS_VENDOR;
9889            }
9890            if ((disabledPkgSetting.pkgPrivateFlags
9891                    & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) {
9892                scanFlags |= SCAN_AS_PRODUCT;
9893            }
9894        }
9895        if (pkgSetting != null) {
9896            final int userId = ((user == null) ? 0 : user.getIdentifier());
9897            if (pkgSetting.getInstantApp(userId)) {
9898                scanFlags |= SCAN_AS_INSTANT_APP;
9899            }
9900            if (pkgSetting.getVirtulalPreload(userId)) {
9901                scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9902            }
9903        }
9904
9905        // Scan as privileged apps that share a user with a priv-app.
9906        if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged()
9907                && (pkg.mSharedUserId != null)) {
9908            SharedUserSetting sharedUserSetting = null;
9909            try {
9910                sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
9911            } catch (PackageManagerException ignore) {}
9912            if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
9913                // Exempt SharedUsers signed with the platform key.
9914                // TODO(b/72378145) Fix this exemption. Force signature apps
9915                // to whitelist their privileged permissions just like other
9916                // priv-apps.
9917                synchronized (mPackages) {
9918                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
9919                    if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
9920                                pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
9921                        scanFlags |= SCAN_AS_PRIVILEGED;
9922                    }
9923                }
9924            }
9925        }
9926
9927        return scanFlags;
9928    }
9929
9930    @GuardedBy("mInstallLock")
9931    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
9932            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9933            @Nullable UserHandle user) throws PackageManagerException {
9934
9935        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9936        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
9937        if (realPkgName != null) {
9938            ensurePackageRenamed(pkg, renamedPkgName);
9939        }
9940        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
9941        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9942        final PackageSetting disabledPkgSetting =
9943                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9944
9945        if (mTransferedPackages.contains(pkg.packageName)) {
9946            Slog.w(TAG, "Package " + pkg.packageName
9947                    + " was transferred to another, but its .apk remains");
9948        }
9949
9950        scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg);
9951        synchronized (mPackages) {
9952            applyPolicy(pkg, parseFlags, scanFlags);
9953            assertPackageIsValid(pkg, parseFlags, scanFlags);
9954
9955            SharedUserSetting sharedUserSetting = null;
9956            if (pkg.mSharedUserId != null) {
9957                // SIDE EFFECTS; may potentially allocate a new shared user
9958                sharedUserSetting = mSettings.getSharedUserLPw(
9959                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9960                if (DEBUG_PACKAGE_SCANNING) {
9961                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
9962                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
9963                                + " (uid=" + sharedUserSetting.userId + "):"
9964                                + " packages=" + sharedUserSetting.packages);
9965                }
9966            }
9967
9968            boolean scanSucceeded = false;
9969            try {
9970                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting,
9971                        disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags,
9972                        (pkg == mPlatformPackage), user);
9973                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
9974                if (result.success) {
9975                    commitScanResultsLocked(request, result);
9976                }
9977                scanSucceeded = true;
9978            } finally {
9979                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9980                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
9981                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9982                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9983                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9984                  }
9985            }
9986        }
9987        return pkg;
9988    }
9989
9990    /**
9991     * Commits the package scan and modifies system state.
9992     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
9993     * of committing the package, leaving the system in an inconsistent state.
9994     * This needs to be fixed so, once we get to this point, no errors are
9995     * possible and the system is not left in an inconsistent state.
9996     */
9997    @GuardedBy("mPackages")
9998    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
9999            throws PackageManagerException {
10000        final PackageParser.Package pkg = request.pkg;
10001        final @ParseFlags int parseFlags = request.parseFlags;
10002        final @ScanFlags int scanFlags = request.scanFlags;
10003        final PackageSetting oldPkgSetting = request.oldPkgSetting;
10004        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10005        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10006        final UserHandle user = request.user;
10007        final String realPkgName = request.realPkgName;
10008        final PackageSetting pkgSetting = result.pkgSetting;
10009        final List<String> changedAbiCodePath = result.changedAbiCodePath;
10010        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
10011
10012        if (newPkgSettingCreated) {
10013            if (originalPkgSetting != null) {
10014                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
10015            }
10016            // THROWS: when we can't allocate a user id. add call to check if there's
10017            // enough space to ensure we won't throw; otherwise, don't modify state
10018            mSettings.addUserToSettingLPw(pkgSetting);
10019
10020            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
10021                mTransferedPackages.add(originalPkgSetting.name);
10022            }
10023        }
10024        // TODO(toddke): Consider a method specifically for modifying the Package object
10025        // post scan; or, moving this stuff out of the Package object since it has nothing
10026        // to do with the package on disk.
10027        // We need to have this here because addUserToSettingLPw() is sometimes responsible
10028        // for creating the application ID. If we did this earlier, we would be saving the
10029        // correct ID.
10030        pkg.applicationInfo.uid = pkgSetting.appId;
10031
10032        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10033
10034        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
10035            mTransferedPackages.add(pkg.packageName);
10036        }
10037
10038        // THROWS: when requested libraries that can't be found. it only changes
10039        // the state of the passed in pkg object, so, move to the top of the method
10040        // and allow it to abort
10041        if ((scanFlags & SCAN_BOOTING) == 0
10042                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10043            // Check all shared libraries and map to their actual file path.
10044            // We only do this here for apps not on a system dir, because those
10045            // are the only ones that can fail an install due to this.  We
10046            // will take care of the system apps by updating all of their
10047            // library paths after the scan is done. Also during the initial
10048            // scan don't update any libs as we do this wholesale after all
10049            // apps are scanned to avoid dependency based scanning.
10050            updateSharedLibrariesLPr(pkg, null);
10051        }
10052
10053        // All versions of a static shared library are referenced with the same
10054        // package name. Internally, we use a synthetic package name to allow
10055        // multiple versions of the same shared library to be installed. So,
10056        // we need to generate the synthetic package name of the latest shared
10057        // library in order to compare signatures.
10058        PackageSetting signatureCheckPs = pkgSetting;
10059        if (pkg.applicationInfo.isStaticSharedLibrary()) {
10060            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10061            if (libraryEntry != null) {
10062                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10063            }
10064        }
10065
10066        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10067        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
10068            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
10069                // We just determined the app is signed correctly, so bring
10070                // over the latest parsed certs.
10071                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10072            } else {
10073                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10074                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10075                            "Package " + pkg.packageName + " upgrade keys do not match the "
10076                                    + "previously installed version");
10077                } else {
10078                    pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10079                    String msg = "System package " + pkg.packageName
10080                            + " signature changed; retaining data.";
10081                    reportSettingsProblem(Log.WARN, msg);
10082                }
10083            }
10084        } else {
10085            try {
10086                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
10087                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
10088                final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting,
10089                        pkg.mSigningDetails, compareCompat, compareRecover);
10090                // The new KeySets will be re-added later in the scanning process.
10091                if (compatMatch) {
10092                    synchronized (mPackages) {
10093                        ksms.removeAppKeySetDataLPw(pkg.packageName);
10094                    }
10095                }
10096                // We just determined the app is signed correctly, so bring
10097                // over the latest parsed certs.
10098                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10099
10100
10101                // if this is is a sharedUser, check to see if the new package is signed by a newer
10102                // signing certificate than the existing one, and if so, copy over the new details
10103                if (signatureCheckPs.sharedUser != null
10104                        && pkg.mSigningDetails.hasAncestor(
10105                                signatureCheckPs.sharedUser.signatures.mSigningDetails)) {
10106                    signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10107                }
10108            } catch (PackageManagerException e) {
10109                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10110                    throw e;
10111                }
10112                // The signature has changed, but this package is in the system
10113                // image...  let's recover!
10114                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10115                // However...  if this package is part of a shared user, but it
10116                // doesn't match the signature of the shared user, let's fail.
10117                // What this means is that you can't change the signatures
10118                // associated with an overall shared user, which doesn't seem all
10119                // that unreasonable.
10120                if (signatureCheckPs.sharedUser != null) {
10121                    if (compareSignatures(
10122                            signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures,
10123                            pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) {
10124                        throw new PackageManagerException(
10125                                INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10126                                "Signature mismatch for shared user: "
10127                                        + pkgSetting.sharedUser);
10128                    }
10129                }
10130                // File a report about this.
10131                String msg = "System package " + pkg.packageName
10132                        + " signature changed; retaining data.";
10133                reportSettingsProblem(Log.WARN, msg);
10134            } catch (IllegalArgumentException e) {
10135
10136                // should never happen: certs matched when checking, but not when comparing
10137                // old to new for sharedUser
10138                throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10139                        "Signing certificates comparison made on incomparable signing details"
10140                        + " but somehow passed verifySignatures!");
10141            }
10142        }
10143
10144        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10145            // This package wants to adopt ownership of permissions from
10146            // another package.
10147            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10148                final String origName = pkg.mAdoptPermissions.get(i);
10149                final PackageSetting orig = mSettings.getPackageLPr(origName);
10150                if (orig != null) {
10151                    if (verifyPackageUpdateLPr(orig, pkg)) {
10152                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
10153                                + pkg.packageName);
10154                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10155                    }
10156                }
10157            }
10158        }
10159
10160        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
10161            for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) {
10162                final String codePathString = changedAbiCodePath.get(i);
10163                try {
10164                    mInstaller.rmdex(codePathString,
10165                            getDexCodeInstructionSet(getPreferredInstructionSet()));
10166                } catch (InstallerException ignored) {
10167                }
10168            }
10169        }
10170
10171        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10172            if (oldPkgSetting != null) {
10173                synchronized (mPackages) {
10174                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
10175                }
10176            }
10177        } else {
10178            final int userId = user == null ? 0 : user.getIdentifier();
10179            // Modify state for the given package setting
10180            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10181                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10182            if (pkgSetting.getInstantApp(userId)) {
10183                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10184            }
10185        }
10186    }
10187
10188    /**
10189     * Returns the "real" name of the package.
10190     * <p>This may differ from the package's actual name if the application has already
10191     * been installed under one of this package's original names.
10192     */
10193    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
10194            @Nullable String renamedPkgName) {
10195        if (isPackageRenamed(pkg, renamedPkgName)) {
10196            return pkg.mRealPackage;
10197        }
10198        return null;
10199    }
10200
10201    /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
10202    private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
10203            @Nullable String renamedPkgName) {
10204        return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
10205    }
10206
10207    /**
10208     * Returns the original package setting.
10209     * <p>A package can migrate its name during an update. In this scenario, a package
10210     * designates a set of names that it considers as one of its original names.
10211     * <p>An original package must be signed identically and it must have the same
10212     * shared user [if any].
10213     */
10214    @GuardedBy("mPackages")
10215    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
10216            @Nullable String renamedPkgName) {
10217        if (!isPackageRenamed(pkg, renamedPkgName)) {
10218            return null;
10219        }
10220        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
10221            final PackageSetting originalPs =
10222                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
10223            if (originalPs != null) {
10224                // the package is already installed under its original name...
10225                // but, should we use it?
10226                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
10227                    // the new package is incompatible with the original
10228                    continue;
10229                } else if (originalPs.sharedUser != null) {
10230                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
10231                        // the shared user id is incompatible with the original
10232                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
10233                                + " to " + pkg.packageName + ": old uid "
10234                                + originalPs.sharedUser.name
10235                                + " differs from " + pkg.mSharedUserId);
10236                        continue;
10237                    }
10238                    // TODO: Add case when shared user id is added [b/28144775]
10239                } else {
10240                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10241                            + pkg.packageName + " to old name " + originalPs.name);
10242                }
10243                return originalPs;
10244            }
10245        }
10246        return null;
10247    }
10248
10249    /**
10250     * Renames the package if it was installed under a different name.
10251     * <p>When we've already installed the package under an original name, update
10252     * the new package so we can continue to have the old name.
10253     */
10254    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10255            @NonNull String renamedPackageName) {
10256        if (pkg.mOriginalPackages == null
10257                || !pkg.mOriginalPackages.contains(renamedPackageName)
10258                || pkg.packageName.equals(renamedPackageName)) {
10259            return;
10260        }
10261        pkg.setPackageName(renamedPackageName);
10262    }
10263
10264    /**
10265     * Just scans the package without any side effects.
10266     * <p>Not entirely true at the moment. There is still one side effect -- this
10267     * method potentially modifies a live {@link PackageSetting} object representing
10268     * the package being scanned. This will be resolved in the future.
10269     *
10270     * @param request Information about the package to be scanned
10271     * @param isUnderFactoryTest Whether or not the device is under factory test
10272     * @param currentTime The current time, in millis
10273     * @return The results of the scan
10274     */
10275    @GuardedBy("mInstallLock")
10276    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10277            boolean isUnderFactoryTest, long currentTime)
10278                    throws PackageManagerException {
10279        final PackageParser.Package pkg = request.pkg;
10280        PackageSetting pkgSetting = request.pkgSetting;
10281        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10282        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10283        final @ParseFlags int parseFlags = request.parseFlags;
10284        final @ScanFlags int scanFlags = request.scanFlags;
10285        final String realPkgName = request.realPkgName;
10286        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10287        final UserHandle user = request.user;
10288        final boolean isPlatformPackage = request.isPlatformPackage;
10289
10290        List<String> changedAbiCodePath = null;
10291
10292        if (DEBUG_PACKAGE_SCANNING) {
10293            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10294                Log.d(TAG, "Scanning package " + pkg.packageName);
10295        }
10296
10297        if (Build.IS_DEBUGGABLE &&
10298                pkg.isPrivileged() &&
10299                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10300            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10301        }
10302
10303        // Initialize package source and resource directories
10304        final File scanFile = new File(pkg.codePath);
10305        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10306        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10307
10308        // We keep references to the derived CPU Abis from settings in oder to reuse
10309        // them in the case where we're not upgrading or booting for the first time.
10310        String primaryCpuAbiFromSettings = null;
10311        String secondaryCpuAbiFromSettings = null;
10312        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10313
10314        if (!needToDeriveAbi) {
10315            if (pkgSetting != null) {
10316                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10317                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10318            } else {
10319                // Re-scanning a system package after uninstalling updates; need to derive ABI
10320                needToDeriveAbi = true;
10321            }
10322        }
10323
10324        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10325            PackageManagerService.reportSettingsProblem(Log.WARN,
10326                    "Package " + pkg.packageName + " shared user changed from "
10327                            + (pkgSetting.sharedUser != null
10328                            ? pkgSetting.sharedUser.name : "<nothing>")
10329                            + " to "
10330                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10331                            + "; replacing with new");
10332            pkgSetting = null;
10333        }
10334
10335        String[] usesStaticLibraries = null;
10336        if (pkg.usesStaticLibraries != null) {
10337            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10338            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10339        }
10340        final boolean createNewPackage = (pkgSetting == null);
10341        if (createNewPackage) {
10342            final String parentPackageName = (pkg.parentPackage != null)
10343                    ? pkg.parentPackage.packageName : null;
10344            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10345            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10346            // REMOVE SharedUserSetting from method; update in a separate call
10347            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10348                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10349                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10350                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10351                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10352                    user, true /*allowInstall*/, instantApp, virtualPreload,
10353                    parentPackageName, pkg.getChildPackageNames(),
10354                    UserManagerService.getInstance(), usesStaticLibraries,
10355                    pkg.usesStaticLibrariesVersions);
10356        } else {
10357            // REMOVE SharedUserSetting from method; update in a separate call.
10358            //
10359            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10360            // secondaryCpuAbi are not known at this point so we always update them
10361            // to null here, only to reset them at a later point.
10362            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10363                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
10364                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10365                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10366                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10367                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10368        }
10369        if (createNewPackage && originalPkgSetting != null) {
10370            // This is the initial transition from the original package, so,
10371            // fix up the new package's name now. We must do this after looking
10372            // up the package under its new name, so getPackageLP takes care of
10373            // fiddling things correctly.
10374            pkg.setPackageName(originalPkgSetting.name);
10375
10376            // File a report about this.
10377            String msg = "New package " + pkgSetting.realName
10378                    + " renamed to replace old package " + pkgSetting.name;
10379            reportSettingsProblem(Log.WARN, msg);
10380        }
10381
10382        if (disabledPkgSetting != null) {
10383            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10384        }
10385
10386        // SELinux sandboxes become more restrictive as targetSdkVersion increases.
10387        // To ensure that apps with sharedUserId are placed in the same selinux domain
10388        // without breaking any assumptions about access, put them into the least
10389        // restrictive targetSdkVersion=25 domain.
10390        // TODO(b/72290969): Base this on the actual targetSdkVersion(s) of the apps within the
10391        // sharedUserSetting, instead of defaulting to the least restrictive domain.
10392        final int targetSdk = (sharedUserSetting != null) ? 25
10393                : pkg.applicationInfo.targetSdkVersion;
10394        // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync.
10395        // They currently can be if the sharedUser apps are signed with the platform key.
10396        final boolean isPrivileged = (sharedUserSetting != null) ?
10397            sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged();
10398
10399        SELinuxMMAC.assignSeInfoValue(pkg, isPrivileged, targetSdk);
10400
10401        pkg.mExtras = pkgSetting;
10402        pkg.applicationInfo.processName = fixProcessName(
10403                pkg.applicationInfo.packageName,
10404                pkg.applicationInfo.processName);
10405
10406        if (!isPlatformPackage) {
10407            // Get all of our default paths setup
10408            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10409        }
10410
10411        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10412
10413        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10414            if (needToDeriveAbi) {
10415                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10416                final boolean extractNativeLibs = !pkg.isLibrary();
10417                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10418                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10419
10420                // Some system apps still use directory structure for native libraries
10421                // in which case we might end up not detecting abi solely based on apk
10422                // structure. Try to detect abi based on directory structure.
10423                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10424                        pkg.applicationInfo.primaryCpuAbi == null) {
10425                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10426                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10427                }
10428            } else {
10429                // This is not a first boot or an upgrade, don't bother deriving the
10430                // ABI during the scan. Instead, trust the value that was stored in the
10431                // package setting.
10432                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10433                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10434
10435                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10436
10437                if (DEBUG_ABI_SELECTION) {
10438                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10439                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10440                            pkg.applicationInfo.secondaryCpuAbi);
10441                }
10442            }
10443        } else {
10444            if ((scanFlags & SCAN_MOVE) != 0) {
10445                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10446                // but we already have this packages package info in the PackageSetting. We just
10447                // use that and derive the native library path based on the new codepath.
10448                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10449                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10450            }
10451
10452            // Set native library paths again. For moves, the path will be updated based on the
10453            // ABIs we've determined above. For non-moves, the path will be updated based on the
10454            // ABIs we determined during compilation, but the path will depend on the final
10455            // package path (after the rename away from the stage path).
10456            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10457        }
10458
10459        // This is a special case for the "system" package, where the ABI is
10460        // dictated by the zygote configuration (and init.rc). We should keep track
10461        // of this ABI so that we can deal with "normal" applications that run under
10462        // the same UID correctly.
10463        if (isPlatformPackage) {
10464            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10465                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10466        }
10467
10468        // If there's a mismatch between the abi-override in the package setting
10469        // and the abiOverride specified for the install. Warn about this because we
10470        // would've already compiled the app without taking the package setting into
10471        // account.
10472        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10473            if (cpuAbiOverride == null && pkg.packageName != null) {
10474                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10475                        " for package " + pkg.packageName);
10476            }
10477        }
10478
10479        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10480        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10481        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10482
10483        // Copy the derived override back to the parsed package, so that we can
10484        // update the package settings accordingly.
10485        pkg.cpuAbiOverride = cpuAbiOverride;
10486
10487        if (DEBUG_ABI_SELECTION) {
10488            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
10489                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10490                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10491        }
10492
10493        // Push the derived path down into PackageSettings so we know what to
10494        // clean up at uninstall time.
10495        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10496
10497        if (DEBUG_ABI_SELECTION) {
10498            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10499                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10500                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10501        }
10502
10503        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10504            // We don't do this here during boot because we can do it all
10505            // at once after scanning all existing packages.
10506            //
10507            // We also do this *before* we perform dexopt on this package, so that
10508            // we can avoid redundant dexopts, and also to make sure we've got the
10509            // code and package path correct.
10510            changedAbiCodePath =
10511                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10512        }
10513
10514        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10515                android.Manifest.permission.FACTORY_TEST)) {
10516            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10517        }
10518
10519        if (isSystemApp(pkg)) {
10520            pkgSetting.isOrphaned = true;
10521        }
10522
10523        // Take care of first install / last update times.
10524        final long scanFileTime = getLastModifiedTime(pkg);
10525        if (currentTime != 0) {
10526            if (pkgSetting.firstInstallTime == 0) {
10527                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10528            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10529                pkgSetting.lastUpdateTime = currentTime;
10530            }
10531        } else if (pkgSetting.firstInstallTime == 0) {
10532            // We need *something*.  Take time time stamp of the file.
10533            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10534        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10535            if (scanFileTime != pkgSetting.timeStamp) {
10536                // A package on the system image has changed; consider this
10537                // to be an update.
10538                pkgSetting.lastUpdateTime = scanFileTime;
10539            }
10540        }
10541        pkgSetting.setTimeStamp(scanFileTime);
10542
10543        pkgSetting.pkg = pkg;
10544        pkgSetting.pkgFlags = pkg.applicationInfo.flags;
10545        if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
10546            pkgSetting.versionCode = pkg.getLongVersionCode();
10547        }
10548        // Update volume if needed
10549        final String volumeUuid = pkg.applicationInfo.volumeUuid;
10550        if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
10551            Slog.i(PackageManagerService.TAG,
10552                    "Update" + (pkgSetting.isSystem() ? " system" : "")
10553                    + " package " + pkg.packageName
10554                    + " volume from " + pkgSetting.volumeUuid
10555                    + " to " + volumeUuid);
10556            pkgSetting.volumeUuid = volumeUuid;
10557        }
10558
10559        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10560    }
10561
10562    /**
10563     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10564     */
10565    private static boolean apkHasCode(String fileName) {
10566        StrictJarFile jarFile = null;
10567        try {
10568            jarFile = new StrictJarFile(fileName,
10569                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10570            return jarFile.findEntry("classes.dex") != null;
10571        } catch (IOException ignore) {
10572        } finally {
10573            try {
10574                if (jarFile != null) {
10575                    jarFile.close();
10576                }
10577            } catch (IOException ignore) {}
10578        }
10579        return false;
10580    }
10581
10582    /**
10583     * Enforces code policy for the package. This ensures that if an APK has
10584     * declared hasCode="true" in its manifest that the APK actually contains
10585     * code.
10586     *
10587     * @throws PackageManagerException If bytecode could not be found when it should exist
10588     */
10589    private static void assertCodePolicy(PackageParser.Package pkg)
10590            throws PackageManagerException {
10591        final boolean shouldHaveCode =
10592                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10593        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10594            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10595                    "Package " + pkg.baseCodePath + " code is missing");
10596        }
10597
10598        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10599            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10600                final boolean splitShouldHaveCode =
10601                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10602                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10603                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10604                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10605                }
10606            }
10607        }
10608    }
10609
10610    /**
10611     * Applies policy to the parsed package based upon the given policy flags.
10612     * Ensures the package is in a good state.
10613     * <p>
10614     * Implementation detail: This method must NOT have any side effect. It would
10615     * ideally be static, but, it requires locks to read system state.
10616     */
10617    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10618            final @ScanFlags int scanFlags) {
10619        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10620            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10621            if (pkg.applicationInfo.isDirectBootAware()) {
10622                // we're direct boot aware; set for all components
10623                for (PackageParser.Service s : pkg.services) {
10624                    s.info.encryptionAware = s.info.directBootAware = true;
10625                }
10626                for (PackageParser.Provider p : pkg.providers) {
10627                    p.info.encryptionAware = p.info.directBootAware = true;
10628                }
10629                for (PackageParser.Activity a : pkg.activities) {
10630                    a.info.encryptionAware = a.info.directBootAware = true;
10631                }
10632                for (PackageParser.Activity r : pkg.receivers) {
10633                    r.info.encryptionAware = r.info.directBootAware = true;
10634                }
10635            }
10636            if (compressedFileExists(pkg.codePath)) {
10637                pkg.isStub = true;
10638            }
10639        } else {
10640            // non system apps can't be flagged as core
10641            pkg.coreApp = false;
10642            // clear flags not applicable to regular apps
10643            pkg.applicationInfo.flags &=
10644                    ~ApplicationInfo.FLAG_PERSISTENT;
10645            pkg.applicationInfo.privateFlags &=
10646                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10647            pkg.applicationInfo.privateFlags &=
10648                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10649            // cap permission priorities
10650            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10651                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10652                    pkg.permissionGroups.get(i).info.priority = 0;
10653                }
10654            }
10655        }
10656        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10657            // clear protected broadcasts
10658            pkg.protectedBroadcasts = null;
10659            // ignore export request for single user receivers
10660            if (pkg.receivers != null) {
10661                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10662                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10663                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10664                        receiver.info.exported = false;
10665                    }
10666                }
10667            }
10668            // ignore export request for single user services
10669            if (pkg.services != null) {
10670                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10671                    final PackageParser.Service service = pkg.services.get(i);
10672                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10673                        service.info.exported = false;
10674                    }
10675                }
10676            }
10677            // ignore export request for single user providers
10678            if (pkg.providers != null) {
10679                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10680                    final PackageParser.Provider provider = pkg.providers.get(i);
10681                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10682                        provider.info.exported = false;
10683                    }
10684                }
10685            }
10686        }
10687
10688        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10689            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10690        }
10691
10692        if ((scanFlags & SCAN_AS_OEM) != 0) {
10693            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10694        }
10695
10696        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10697            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10698        }
10699
10700        if ((scanFlags & SCAN_AS_PRODUCT) != 0) {
10701            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT;
10702        }
10703
10704        if (!isSystemApp(pkg)) {
10705            // Only system apps can use these features.
10706            pkg.mOriginalPackages = null;
10707            pkg.mRealPackage = null;
10708            pkg.mAdoptPermissions = null;
10709        }
10710    }
10711
10712    private static @NonNull <T> T assertNotNull(@Nullable T object, String message)
10713            throws PackageManagerException {
10714        if (object == null) {
10715            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message);
10716        }
10717        return object;
10718    }
10719
10720    /**
10721     * Asserts the parsed package is valid according to the given policy. If the
10722     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10723     * <p>
10724     * Implementation detail: This method must NOT have any side effects. It would
10725     * ideally be static, but, it requires locks to read system state.
10726     *
10727     * @throws PackageManagerException If the package fails any of the validation checks
10728     */
10729    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10730            final @ScanFlags int scanFlags)
10731                    throws PackageManagerException {
10732        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10733            assertCodePolicy(pkg);
10734        }
10735
10736        if (pkg.applicationInfo.getCodePath() == null ||
10737                pkg.applicationInfo.getResourcePath() == null) {
10738            // Bail out. The resource and code paths haven't been set.
10739            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10740                    "Code and resource paths haven't been set correctly");
10741        }
10742
10743        // Make sure we're not adding any bogus keyset info
10744        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10745        ksms.assertScannedPackageValid(pkg);
10746
10747        synchronized (mPackages) {
10748            // The special "android" package can only be defined once
10749            if (pkg.packageName.equals("android")) {
10750                if (mAndroidApplication != null) {
10751                    Slog.w(TAG, "*************************************************");
10752                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10753                    Slog.w(TAG, " codePath=" + pkg.codePath);
10754                    Slog.w(TAG, "*************************************************");
10755                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10756                            "Core android package being redefined.  Skipping.");
10757                }
10758            }
10759
10760            // A package name must be unique; don't allow duplicates
10761            if (mPackages.containsKey(pkg.packageName)) {
10762                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10763                        "Application package " + pkg.packageName
10764                        + " already installed.  Skipping duplicate.");
10765            }
10766
10767            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10768                // Static libs have a synthetic package name containing the version
10769                // but we still want the base name to be unique.
10770                if (mPackages.containsKey(pkg.manifestPackageName)) {
10771                    throw new PackageManagerException(
10772                            "Duplicate static shared lib provider package");
10773                }
10774
10775                // Static shared libraries should have at least O target SDK
10776                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10777                    throw new PackageManagerException(
10778                            "Packages declaring static-shared libs must target O SDK or higher");
10779                }
10780
10781                // Package declaring static a shared lib cannot be instant apps
10782                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10783                    throw new PackageManagerException(
10784                            "Packages declaring static-shared libs cannot be instant apps");
10785                }
10786
10787                // Package declaring static a shared lib cannot be renamed since the package
10788                // name is synthetic and apps can't code around package manager internals.
10789                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10790                    throw new PackageManagerException(
10791                            "Packages declaring static-shared libs cannot be renamed");
10792                }
10793
10794                // Package declaring static a shared lib cannot declare child packages
10795                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10796                    throw new PackageManagerException(
10797                            "Packages declaring static-shared libs cannot have child packages");
10798                }
10799
10800                // Package declaring static a shared lib cannot declare dynamic libs
10801                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10802                    throw new PackageManagerException(
10803                            "Packages declaring static-shared libs cannot declare dynamic libs");
10804                }
10805
10806                // Package declaring static a shared lib cannot declare shared users
10807                if (pkg.mSharedUserId != null) {
10808                    throw new PackageManagerException(
10809                            "Packages declaring static-shared libs cannot declare shared users");
10810                }
10811
10812                // Static shared libs cannot declare activities
10813                if (!pkg.activities.isEmpty()) {
10814                    throw new PackageManagerException(
10815                            "Static shared libs cannot declare activities");
10816                }
10817
10818                // Static shared libs cannot declare services
10819                if (!pkg.services.isEmpty()) {
10820                    throw new PackageManagerException(
10821                            "Static shared libs cannot declare services");
10822                }
10823
10824                // Static shared libs cannot declare providers
10825                if (!pkg.providers.isEmpty()) {
10826                    throw new PackageManagerException(
10827                            "Static shared libs cannot declare content providers");
10828                }
10829
10830                // Static shared libs cannot declare receivers
10831                if (!pkg.receivers.isEmpty()) {
10832                    throw new PackageManagerException(
10833                            "Static shared libs cannot declare broadcast receivers");
10834                }
10835
10836                // Static shared libs cannot declare permission groups
10837                if (!pkg.permissionGroups.isEmpty()) {
10838                    throw new PackageManagerException(
10839                            "Static shared libs cannot declare permission groups");
10840                }
10841
10842                // Static shared libs cannot declare permissions
10843                if (!pkg.permissions.isEmpty()) {
10844                    throw new PackageManagerException(
10845                            "Static shared libs cannot declare permissions");
10846                }
10847
10848                // Static shared libs cannot declare protected broadcasts
10849                if (pkg.protectedBroadcasts != null) {
10850                    throw new PackageManagerException(
10851                            "Static shared libs cannot declare protected broadcasts");
10852                }
10853
10854                // Static shared libs cannot be overlay targets
10855                if (pkg.mOverlayTarget != null) {
10856                    throw new PackageManagerException(
10857                            "Static shared libs cannot be overlay targets");
10858                }
10859
10860                // The version codes must be ordered as lib versions
10861                long minVersionCode = Long.MIN_VALUE;
10862                long maxVersionCode = Long.MAX_VALUE;
10863
10864                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10865                        pkg.staticSharedLibName);
10866                if (versionedLib != null) {
10867                    final int versionCount = versionedLib.size();
10868                    for (int i = 0; i < versionCount; i++) {
10869                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10870                        final long libVersionCode = libInfo.getDeclaringPackage()
10871                                .getLongVersionCode();
10872                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
10873                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10874                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
10875                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10876                        } else {
10877                            minVersionCode = maxVersionCode = libVersionCode;
10878                            break;
10879                        }
10880                    }
10881                }
10882                if (pkg.getLongVersionCode() < minVersionCode
10883                        || pkg.getLongVersionCode() > maxVersionCode) {
10884                    throw new PackageManagerException("Static shared"
10885                            + " lib version codes must be ordered as lib versions");
10886                }
10887            }
10888
10889            // Only privileged apps and updated privileged apps can add child packages.
10890            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10891                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10892                    throw new PackageManagerException("Only privileged apps can add child "
10893                            + "packages. Ignoring package " + pkg.packageName);
10894                }
10895                final int childCount = pkg.childPackages.size();
10896                for (int i = 0; i < childCount; i++) {
10897                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10898                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10899                            childPkg.packageName)) {
10900                        throw new PackageManagerException("Can't override child of "
10901                                + "another disabled app. Ignoring package " + pkg.packageName);
10902                    }
10903                }
10904            }
10905
10906            // If we're only installing presumed-existing packages, require that the
10907            // scanned APK is both already known and at the path previously established
10908            // for it.  Previously unknown packages we pick up normally, but if we have an
10909            // a priori expectation about this package's install presence, enforce it.
10910            // With a singular exception for new system packages. When an OTA contains
10911            // a new system package, we allow the codepath to change from a system location
10912            // to the user-installed location. If we don't allow this change, any newer,
10913            // user-installed version of the application will be ignored.
10914            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10915                if (mExpectingBetter.containsKey(pkg.packageName)) {
10916                    logCriticalInfo(Log.WARN,
10917                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10918                } else {
10919                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10920                    if (known != null) {
10921                        if (DEBUG_PACKAGE_SCANNING) {
10922                            Log.d(TAG, "Examining " + pkg.codePath
10923                                    + " and requiring known paths " + known.codePathString
10924                                    + " & " + known.resourcePathString);
10925                        }
10926                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10927                                || !pkg.applicationInfo.getResourcePath().equals(
10928                                        known.resourcePathString)) {
10929                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10930                                    "Application package " + pkg.packageName
10931                                    + " found at " + pkg.applicationInfo.getCodePath()
10932                                    + " but expected at " + known.codePathString
10933                                    + "; ignoring.");
10934                        }
10935                    } else {
10936                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10937                                "Application package " + pkg.packageName
10938                                + " not found; ignoring.");
10939                    }
10940                }
10941            }
10942
10943            // Verify that this new package doesn't have any content providers
10944            // that conflict with existing packages.  Only do this if the
10945            // package isn't already installed, since we don't want to break
10946            // things that are installed.
10947            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10948                final int N = pkg.providers.size();
10949                int i;
10950                for (i=0; i<N; i++) {
10951                    PackageParser.Provider p = pkg.providers.get(i);
10952                    if (p.info.authority != null) {
10953                        String names[] = p.info.authority.split(";");
10954                        for (int j = 0; j < names.length; j++) {
10955                            if (mProvidersByAuthority.containsKey(names[j])) {
10956                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10957                                final String otherPackageName =
10958                                        ((other != null && other.getComponentName() != null) ?
10959                                                other.getComponentName().getPackageName() : "?");
10960                                throw new PackageManagerException(
10961                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10962                                        "Can't install because provider name " + names[j]
10963                                                + " (in package " + pkg.applicationInfo.packageName
10964                                                + ") is already used by " + otherPackageName);
10965                            }
10966                        }
10967                    }
10968                }
10969            }
10970
10971            // Verify that packages sharing a user with a privileged app are marked as privileged.
10972            if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
10973                SharedUserSetting sharedUserSetting = null;
10974                try {
10975                    sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
10976                } catch (PackageManagerException ignore) {}
10977                if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
10978                    // Exempt SharedUsers signed with the platform key.
10979                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
10980                    if ((platformPkgSetting.signatures.mSigningDetails
10981                            != PackageParser.SigningDetails.UNKNOWN)
10982                            && (compareSignatures(
10983                                    platformPkgSetting.signatures.mSigningDetails.signatures,
10984                                    pkg.mSigningDetails.signatures)
10985                                            != PackageManager.SIGNATURE_MATCH)) {
10986                        throw new PackageManagerException("Apps that share a user with a " +
10987                                "privileged app must themselves be marked as privileged. " +
10988                                pkg.packageName + " shares privileged user " +
10989                                pkg.mSharedUserId + ".");
10990                    }
10991                }
10992            }
10993
10994            // Apply policies specific for runtime resource overlays (RROs).
10995            if (pkg.mOverlayTarget != null) {
10996                // System overlays have some restrictions on their use of the 'static' state.
10997                if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10998                    // We are scanning a system overlay. This can be the first scan of the
10999                    // system/vendor/oem partition, or an update to the system overlay.
11000                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
11001                        // This must be an update to a system overlay.
11002                        final PackageSetting previousPkg = assertNotNull(
11003                                mSettings.getPackageLPr(pkg.packageName),
11004                                "previous package state not present");
11005
11006                        // Static overlays cannot be updated.
11007                        if (previousPkg.pkg.mOverlayIsStatic) {
11008                            throw new PackageManagerException("Overlay " + pkg.packageName +
11009                                    " is static and cannot be upgraded.");
11010                        // Non-static overlays cannot be converted to static overlays.
11011                        } else if (pkg.mOverlayIsStatic) {
11012                            throw new PackageManagerException("Overlay " + pkg.packageName +
11013                                    " cannot be upgraded into a static overlay.");
11014                        }
11015                    }
11016                } else {
11017                    // The overlay is a non-system overlay. Non-system overlays cannot be static.
11018                    if (pkg.mOverlayIsStatic) {
11019                        throw new PackageManagerException("Overlay " + pkg.packageName +
11020                                " is static but not pre-installed.");
11021                    }
11022
11023                    // The only case where we allow installation of a non-system overlay is when
11024                    // its signature is signed with the platform certificate.
11025                    PackageSetting platformPkgSetting = mSettings.getPackageLPr("android");
11026                    if ((platformPkgSetting.signatures.mSigningDetails
11027                            != PackageParser.SigningDetails.UNKNOWN)
11028                            && (compareSignatures(
11029                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11030                                    pkg.mSigningDetails.signatures)
11031                                            != PackageManager.SIGNATURE_MATCH)) {
11032                        throw new PackageManagerException("Overlay " + pkg.packageName +
11033                                " must be signed with the platform certificate.");
11034                    }
11035                }
11036            }
11037        }
11038    }
11039
11040    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
11041            int type, String declaringPackageName, long declaringVersionCode) {
11042        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11043        if (versionedLib == null) {
11044            versionedLib = new LongSparseArray<>();
11045            mSharedLibraries.put(name, versionedLib);
11046            if (type == SharedLibraryInfo.TYPE_STATIC) {
11047                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11048            }
11049        } else if (versionedLib.indexOfKey(version) >= 0) {
11050            return false;
11051        }
11052        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11053                version, type, declaringPackageName, declaringVersionCode);
11054        versionedLib.put(version, libEntry);
11055        return true;
11056    }
11057
11058    private boolean removeSharedLibraryLPw(String name, long version) {
11059        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11060        if (versionedLib == null) {
11061            return false;
11062        }
11063        final int libIdx = versionedLib.indexOfKey(version);
11064        if (libIdx < 0) {
11065            return false;
11066        }
11067        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11068        versionedLib.remove(version);
11069        if (versionedLib.size() <= 0) {
11070            mSharedLibraries.remove(name);
11071            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11072                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11073                        .getPackageName());
11074            }
11075        }
11076        return true;
11077    }
11078
11079    /**
11080     * Adds a scanned package to the system. When this method is finished, the package will
11081     * be available for query, resolution, etc...
11082     */
11083    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11084            UserHandle user, final @ScanFlags int scanFlags, boolean chatty) {
11085        final String pkgName = pkg.packageName;
11086        if (mCustomResolverComponentName != null &&
11087                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11088            setUpCustomResolverActivity(pkg);
11089        }
11090
11091        if (pkg.packageName.equals("android")) {
11092            synchronized (mPackages) {
11093                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11094                    // Set up information for our fall-back user intent resolution activity.
11095                    mPlatformPackage = pkg;
11096                    pkg.mVersionCode = mSdkVersion;
11097                    pkg.mVersionCodeMajor = 0;
11098                    mAndroidApplication = pkg.applicationInfo;
11099                    if (!mResolverReplaced) {
11100                        mResolveActivity.applicationInfo = mAndroidApplication;
11101                        mResolveActivity.name = ResolverActivity.class.getName();
11102                        mResolveActivity.packageName = mAndroidApplication.packageName;
11103                        mResolveActivity.processName = "system:ui";
11104                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11105                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11106                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11107                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11108                        mResolveActivity.exported = true;
11109                        mResolveActivity.enabled = true;
11110                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11111                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11112                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11113                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11114                                | ActivityInfo.CONFIG_ORIENTATION
11115                                | ActivityInfo.CONFIG_KEYBOARD
11116                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11117                        mResolveInfo.activityInfo = mResolveActivity;
11118                        mResolveInfo.priority = 0;
11119                        mResolveInfo.preferredOrder = 0;
11120                        mResolveInfo.match = 0;
11121                        mResolveComponentName = new ComponentName(
11122                                mAndroidApplication.packageName, mResolveActivity.name);
11123                    }
11124                }
11125            }
11126        }
11127
11128        ArrayList<PackageParser.Package> clientLibPkgs = null;
11129        // writer
11130        synchronized (mPackages) {
11131            boolean hasStaticSharedLibs = false;
11132
11133            // Any app can add new static shared libraries
11134            if (pkg.staticSharedLibName != null) {
11135                // Static shared libs don't allow renaming as they have synthetic package
11136                // names to allow install of multiple versions, so use name from manifest.
11137                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11138                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11139                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
11140                    hasStaticSharedLibs = true;
11141                } else {
11142                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11143                                + pkg.staticSharedLibName + " already exists; skipping");
11144                }
11145                // Static shared libs cannot be updated once installed since they
11146                // use synthetic package name which includes the version code, so
11147                // not need to update other packages's shared lib dependencies.
11148            }
11149
11150            if (!hasStaticSharedLibs
11151                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11152                // Only system apps can add new dynamic shared libraries.
11153                if (pkg.libraryNames != null) {
11154                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11155                        String name = pkg.libraryNames.get(i);
11156                        boolean allowed = false;
11157                        if (pkg.isUpdatedSystemApp()) {
11158                            // New library entries can only be added through the
11159                            // system image.  This is important to get rid of a lot
11160                            // of nasty edge cases: for example if we allowed a non-
11161                            // system update of the app to add a library, then uninstalling
11162                            // the update would make the library go away, and assumptions
11163                            // we made such as through app install filtering would now
11164                            // have allowed apps on the device which aren't compatible
11165                            // with it.  Better to just have the restriction here, be
11166                            // conservative, and create many fewer cases that can negatively
11167                            // impact the user experience.
11168                            final PackageSetting sysPs = mSettings
11169                                    .getDisabledSystemPkgLPr(pkg.packageName);
11170                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11171                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11172                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11173                                        allowed = true;
11174                                        break;
11175                                    }
11176                                }
11177                            }
11178                        } else {
11179                            allowed = true;
11180                        }
11181                        if (allowed) {
11182                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11183                                    SharedLibraryInfo.VERSION_UNDEFINED,
11184                                    SharedLibraryInfo.TYPE_DYNAMIC,
11185                                    pkg.packageName, pkg.getLongVersionCode())) {
11186                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11187                                        + name + " already exists; skipping");
11188                            }
11189                        } else {
11190                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11191                                    + name + " that is not declared on system image; skipping");
11192                        }
11193                    }
11194
11195                    if ((scanFlags & SCAN_BOOTING) == 0) {
11196                        // If we are not booting, we need to update any applications
11197                        // that are clients of our shared library.  If we are booting,
11198                        // this will all be done once the scan is complete.
11199                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11200                    }
11201                }
11202            }
11203        }
11204
11205        if ((scanFlags & SCAN_BOOTING) != 0) {
11206            // No apps can run during boot scan, so they don't need to be frozen
11207        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11208            // Caller asked to not kill app, so it's probably not frozen
11209        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11210            // Caller asked us to ignore frozen check for some reason; they
11211            // probably didn't know the package name
11212        } else {
11213            // We're doing major surgery on this package, so it better be frozen
11214            // right now to keep it from launching
11215            checkPackageFrozen(pkgName);
11216        }
11217
11218        // Also need to kill any apps that are dependent on the library.
11219        if (clientLibPkgs != null) {
11220            for (int i=0; i<clientLibPkgs.size(); i++) {
11221                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11222                killApplication(clientPkg.applicationInfo.packageName,
11223                        clientPkg.applicationInfo.uid, "update lib");
11224            }
11225        }
11226
11227        // writer
11228        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11229
11230        synchronized (mPackages) {
11231            // We don't expect installation to fail beyond this point
11232
11233            // Add the new setting to mSettings
11234            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11235            // Add the new setting to mPackages
11236            mPackages.put(pkg.applicationInfo.packageName, pkg);
11237            // Make sure we don't accidentally delete its data.
11238            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11239            while (iter.hasNext()) {
11240                PackageCleanItem item = iter.next();
11241                if (pkgName.equals(item.packageName)) {
11242                    iter.remove();
11243                }
11244            }
11245
11246            // Add the package's KeySets to the global KeySetManagerService
11247            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11248            ksms.addScannedPackageLPw(pkg);
11249
11250            int N = pkg.providers.size();
11251            StringBuilder r = null;
11252            int i;
11253            for (i=0; i<N; i++) {
11254                PackageParser.Provider p = pkg.providers.get(i);
11255                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11256                        p.info.processName);
11257                mProviders.addProvider(p);
11258                p.syncable = p.info.isSyncable;
11259                if (p.info.authority != null) {
11260                    String names[] = p.info.authority.split(";");
11261                    p.info.authority = null;
11262                    for (int j = 0; j < names.length; j++) {
11263                        if (j == 1 && p.syncable) {
11264                            // We only want the first authority for a provider to possibly be
11265                            // syncable, so if we already added this provider using a different
11266                            // authority clear the syncable flag. We copy the provider before
11267                            // changing it because the mProviders object contains a reference
11268                            // to a provider that we don't want to change.
11269                            // Only do this for the second authority since the resulting provider
11270                            // object can be the same for all future authorities for this provider.
11271                            p = new PackageParser.Provider(p);
11272                            p.syncable = false;
11273                        }
11274                        if (!mProvidersByAuthority.containsKey(names[j])) {
11275                            mProvidersByAuthority.put(names[j], p);
11276                            if (p.info.authority == null) {
11277                                p.info.authority = names[j];
11278                            } else {
11279                                p.info.authority = p.info.authority + ";" + names[j];
11280                            }
11281                            if (DEBUG_PACKAGE_SCANNING) {
11282                                if (chatty)
11283                                    Log.d(TAG, "Registered content provider: " + names[j]
11284                                            + ", className = " + p.info.name + ", isSyncable = "
11285                                            + p.info.isSyncable);
11286                            }
11287                        } else {
11288                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11289                            Slog.w(TAG, "Skipping provider name " + names[j] +
11290                                    " (in package " + pkg.applicationInfo.packageName +
11291                                    "): name already used by "
11292                                    + ((other != null && other.getComponentName() != null)
11293                                            ? other.getComponentName().getPackageName() : "?"));
11294                        }
11295                    }
11296                }
11297                if (chatty) {
11298                    if (r == null) {
11299                        r = new StringBuilder(256);
11300                    } else {
11301                        r.append(' ');
11302                    }
11303                    r.append(p.info.name);
11304                }
11305            }
11306            if (r != null) {
11307                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11308            }
11309
11310            N = pkg.services.size();
11311            r = null;
11312            for (i=0; i<N; i++) {
11313                PackageParser.Service s = pkg.services.get(i);
11314                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11315                        s.info.processName);
11316                mServices.addService(s);
11317                if (chatty) {
11318                    if (r == null) {
11319                        r = new StringBuilder(256);
11320                    } else {
11321                        r.append(' ');
11322                    }
11323                    r.append(s.info.name);
11324                }
11325            }
11326            if (r != null) {
11327                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11328            }
11329
11330            N = pkg.receivers.size();
11331            r = null;
11332            for (i=0; i<N; i++) {
11333                PackageParser.Activity a = pkg.receivers.get(i);
11334                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11335                        a.info.processName);
11336                mReceivers.addActivity(a, "receiver");
11337                if (chatty) {
11338                    if (r == null) {
11339                        r = new StringBuilder(256);
11340                    } else {
11341                        r.append(' ');
11342                    }
11343                    r.append(a.info.name);
11344                }
11345            }
11346            if (r != null) {
11347                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11348            }
11349
11350            N = pkg.activities.size();
11351            r = null;
11352            for (i=0; i<N; i++) {
11353                PackageParser.Activity a = pkg.activities.get(i);
11354                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11355                        a.info.processName);
11356                mActivities.addActivity(a, "activity");
11357                if (chatty) {
11358                    if (r == null) {
11359                        r = new StringBuilder(256);
11360                    } else {
11361                        r.append(' ');
11362                    }
11363                    r.append(a.info.name);
11364                }
11365            }
11366            if (r != null) {
11367                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11368            }
11369
11370            // Don't allow ephemeral applications to define new permissions groups.
11371            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11372                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11373                        + " ignored: instant apps cannot define new permission groups.");
11374            } else {
11375                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11376            }
11377
11378            // Don't allow ephemeral applications to define new permissions.
11379            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11380                Slog.w(TAG, "Permissions from package " + pkg.packageName
11381                        + " ignored: instant apps cannot define new permissions.");
11382            } else {
11383                mPermissionManager.addAllPermissions(pkg, chatty);
11384            }
11385
11386            N = pkg.instrumentation.size();
11387            r = null;
11388            for (i=0; i<N; i++) {
11389                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11390                a.info.packageName = pkg.applicationInfo.packageName;
11391                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11392                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11393                a.info.splitNames = pkg.splitNames;
11394                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11395                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11396                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11397                a.info.dataDir = pkg.applicationInfo.dataDir;
11398                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11399                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11400                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11401                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11402                mInstrumentation.put(a.getComponentName(), a);
11403                if (chatty) {
11404                    if (r == null) {
11405                        r = new StringBuilder(256);
11406                    } else {
11407                        r.append(' ');
11408                    }
11409                    r.append(a.info.name);
11410                }
11411            }
11412            if (r != null) {
11413                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11414            }
11415
11416            if (pkg.protectedBroadcasts != null) {
11417                N = pkg.protectedBroadcasts.size();
11418                synchronized (mProtectedBroadcasts) {
11419                    for (i = 0; i < N; i++) {
11420                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11421                    }
11422                }
11423            }
11424        }
11425
11426        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11427    }
11428
11429    /**
11430     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11431     * is derived purely on the basis of the contents of {@code scanFile} and
11432     * {@code cpuAbiOverride}.
11433     *
11434     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11435     */
11436    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11437            boolean extractLibs)
11438                    throws PackageManagerException {
11439        // Give ourselves some initial paths; we'll come back for another
11440        // pass once we've determined ABI below.
11441        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11442
11443        // We would never need to extract libs for forward-locked and external packages,
11444        // since the container service will do it for us. We shouldn't attempt to
11445        // extract libs from system app when it was not updated.
11446        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11447                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11448            extractLibs = false;
11449        }
11450
11451        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11452        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11453
11454        NativeLibraryHelper.Handle handle = null;
11455        try {
11456            handle = NativeLibraryHelper.Handle.create(pkg);
11457            // TODO(multiArch): This can be null for apps that didn't go through the
11458            // usual installation process. We can calculate it again, like we
11459            // do during install time.
11460            //
11461            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11462            // unnecessary.
11463            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11464
11465            // Null out the abis so that they can be recalculated.
11466            pkg.applicationInfo.primaryCpuAbi = null;
11467            pkg.applicationInfo.secondaryCpuAbi = null;
11468            if (isMultiArch(pkg.applicationInfo)) {
11469                // Warn if we've set an abiOverride for multi-lib packages..
11470                // By definition, we need to copy both 32 and 64 bit libraries for
11471                // such packages.
11472                if (pkg.cpuAbiOverride != null
11473                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11474                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11475                }
11476
11477                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11478                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11479                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11480                    if (extractLibs) {
11481                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11482                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11483                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11484                                useIsaSpecificSubdirs);
11485                    } else {
11486                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11487                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11488                    }
11489                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11490                }
11491
11492                // Shared library native code should be in the APK zip aligned
11493                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11494                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11495                            "Shared library native lib extraction not supported");
11496                }
11497
11498                maybeThrowExceptionForMultiArchCopy(
11499                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11500
11501                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11502                    if (extractLibs) {
11503                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11504                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11505                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11506                                useIsaSpecificSubdirs);
11507                    } else {
11508                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11509                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11510                    }
11511                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11512                }
11513
11514                maybeThrowExceptionForMultiArchCopy(
11515                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11516
11517                if (abi64 >= 0) {
11518                    // Shared library native libs should be in the APK zip aligned
11519                    if (extractLibs && pkg.isLibrary()) {
11520                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11521                                "Shared library native lib extraction not supported");
11522                    }
11523                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11524                }
11525
11526                if (abi32 >= 0) {
11527                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11528                    if (abi64 >= 0) {
11529                        if (pkg.use32bitAbi) {
11530                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11531                            pkg.applicationInfo.primaryCpuAbi = abi;
11532                        } else {
11533                            pkg.applicationInfo.secondaryCpuAbi = abi;
11534                        }
11535                    } else {
11536                        pkg.applicationInfo.primaryCpuAbi = abi;
11537                    }
11538                }
11539            } else {
11540                String[] abiList = (cpuAbiOverride != null) ?
11541                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11542
11543                // Enable gross and lame hacks for apps that are built with old
11544                // SDK tools. We must scan their APKs for renderscript bitcode and
11545                // not launch them if it's present. Don't bother checking on devices
11546                // that don't have 64 bit support.
11547                boolean needsRenderScriptOverride = false;
11548                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11549                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11550                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11551                    needsRenderScriptOverride = true;
11552                }
11553
11554                final int copyRet;
11555                if (extractLibs) {
11556                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11557                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11558                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11559                } else {
11560                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11561                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11562                }
11563                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11564
11565                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11566                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11567                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11568                }
11569
11570                if (copyRet >= 0) {
11571                    // Shared libraries that have native libs must be multi-architecture
11572                    if (pkg.isLibrary()) {
11573                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11574                                "Shared library with native libs must be multiarch");
11575                    }
11576                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11577                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11578                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11579                } else if (needsRenderScriptOverride) {
11580                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11581                }
11582            }
11583        } catch (IOException ioe) {
11584            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11585        } finally {
11586            IoUtils.closeQuietly(handle);
11587        }
11588
11589        // Now that we've calculated the ABIs and determined if it's an internal app,
11590        // we will go ahead and populate the nativeLibraryPath.
11591        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11592    }
11593
11594    /**
11595     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11596     * i.e, so that all packages can be run inside a single process if required.
11597     *
11598     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11599     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11600     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11601     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11602     * updating a package that belongs to a shared user.
11603     *
11604     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11605     * adds unnecessary complexity.
11606     */
11607    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11608            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11609        List<String> changedAbiCodePath = null;
11610        String requiredInstructionSet = null;
11611        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11612            requiredInstructionSet = VMRuntime.getInstructionSet(
11613                     scannedPackage.applicationInfo.primaryCpuAbi);
11614        }
11615
11616        PackageSetting requirer = null;
11617        for (PackageSetting ps : packagesForUser) {
11618            // If packagesForUser contains scannedPackage, we skip it. This will happen
11619            // when scannedPackage is an update of an existing package. Without this check,
11620            // we will never be able to change the ABI of any package belonging to a shared
11621            // user, even if it's compatible with other packages.
11622            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11623                if (ps.primaryCpuAbiString == null) {
11624                    continue;
11625                }
11626
11627                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11628                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11629                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11630                    // this but there's not much we can do.
11631                    String errorMessage = "Instruction set mismatch, "
11632                            + ((requirer == null) ? "[caller]" : requirer)
11633                            + " requires " + requiredInstructionSet + " whereas " + ps
11634                            + " requires " + instructionSet;
11635                    Slog.w(TAG, errorMessage);
11636                }
11637
11638                if (requiredInstructionSet == null) {
11639                    requiredInstructionSet = instructionSet;
11640                    requirer = ps;
11641                }
11642            }
11643        }
11644
11645        if (requiredInstructionSet != null) {
11646            String adjustedAbi;
11647            if (requirer != null) {
11648                // requirer != null implies that either scannedPackage was null or that scannedPackage
11649                // did not require an ABI, in which case we have to adjust scannedPackage to match
11650                // the ABI of the set (which is the same as requirer's ABI)
11651                adjustedAbi = requirer.primaryCpuAbiString;
11652                if (scannedPackage != null) {
11653                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11654                }
11655            } else {
11656                // requirer == null implies that we're updating all ABIs in the set to
11657                // match scannedPackage.
11658                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11659            }
11660
11661            for (PackageSetting ps : packagesForUser) {
11662                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11663                    if (ps.primaryCpuAbiString != null) {
11664                        continue;
11665                    }
11666
11667                    ps.primaryCpuAbiString = adjustedAbi;
11668                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11669                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11670                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11671                        if (DEBUG_ABI_SELECTION) {
11672                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11673                                    + " (requirer="
11674                                    + (requirer != null ? requirer.pkg : "null")
11675                                    + ", scannedPackage="
11676                                    + (scannedPackage != null ? scannedPackage : "null")
11677                                    + ")");
11678                        }
11679                        if (changedAbiCodePath == null) {
11680                            changedAbiCodePath = new ArrayList<>();
11681                        }
11682                        changedAbiCodePath.add(ps.codePathString);
11683                    }
11684                }
11685            }
11686        }
11687        return changedAbiCodePath;
11688    }
11689
11690    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11691        synchronized (mPackages) {
11692            mResolverReplaced = true;
11693            // Set up information for custom user intent resolution activity.
11694            mResolveActivity.applicationInfo = pkg.applicationInfo;
11695            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11696            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11697            mResolveActivity.processName = pkg.applicationInfo.packageName;
11698            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11699            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11700                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11701            mResolveActivity.theme = 0;
11702            mResolveActivity.exported = true;
11703            mResolveActivity.enabled = true;
11704            mResolveInfo.activityInfo = mResolveActivity;
11705            mResolveInfo.priority = 0;
11706            mResolveInfo.preferredOrder = 0;
11707            mResolveInfo.match = 0;
11708            mResolveComponentName = mCustomResolverComponentName;
11709            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11710                    mResolveComponentName);
11711        }
11712    }
11713
11714    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11715        if (installerActivity == null) {
11716            if (DEBUG_INSTANT) {
11717                Slog.d(TAG, "Clear ephemeral installer activity");
11718            }
11719            mInstantAppInstallerActivity = null;
11720            return;
11721        }
11722
11723        if (DEBUG_INSTANT) {
11724            Slog.d(TAG, "Set ephemeral installer activity: "
11725                    + installerActivity.getComponentName());
11726        }
11727        // Set up information for ephemeral installer activity
11728        mInstantAppInstallerActivity = installerActivity;
11729        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11730                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11731        mInstantAppInstallerActivity.exported = true;
11732        mInstantAppInstallerActivity.enabled = true;
11733        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11734        mInstantAppInstallerInfo.priority = 1;
11735        mInstantAppInstallerInfo.preferredOrder = 1;
11736        mInstantAppInstallerInfo.isDefault = true;
11737        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11738                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11739    }
11740
11741    private static String calculateBundledApkRoot(final String codePathString) {
11742        final File codePath = new File(codePathString);
11743        final File codeRoot;
11744        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11745            codeRoot = Environment.getRootDirectory();
11746        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11747            codeRoot = Environment.getOemDirectory();
11748        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11749            codeRoot = Environment.getVendorDirectory();
11750        } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) {
11751            codeRoot = Environment.getProductDirectory();
11752        } else {
11753            // Unrecognized code path; take its top real segment as the apk root:
11754            // e.g. /something/app/blah.apk => /something
11755            try {
11756                File f = codePath.getCanonicalFile();
11757                File parent = f.getParentFile();    // non-null because codePath is a file
11758                File tmp;
11759                while ((tmp = parent.getParentFile()) != null) {
11760                    f = parent;
11761                    parent = tmp;
11762                }
11763                codeRoot = f;
11764                Slog.w(TAG, "Unrecognized code path "
11765                        + codePath + " - using " + codeRoot);
11766            } catch (IOException e) {
11767                // Can't canonicalize the code path -- shenanigans?
11768                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11769                return Environment.getRootDirectory().getPath();
11770            }
11771        }
11772        return codeRoot.getPath();
11773    }
11774
11775    /**
11776     * Derive and set the location of native libraries for the given package,
11777     * which varies depending on where and how the package was installed.
11778     */
11779    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11780        final ApplicationInfo info = pkg.applicationInfo;
11781        final String codePath = pkg.codePath;
11782        final File codeFile = new File(codePath);
11783        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11784        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11785
11786        info.nativeLibraryRootDir = null;
11787        info.nativeLibraryRootRequiresIsa = false;
11788        info.nativeLibraryDir = null;
11789        info.secondaryNativeLibraryDir = null;
11790
11791        if (isApkFile(codeFile)) {
11792            // Monolithic install
11793            if (bundledApp) {
11794                // If "/system/lib64/apkname" exists, assume that is the per-package
11795                // native library directory to use; otherwise use "/system/lib/apkname".
11796                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11797                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11798                        getPrimaryInstructionSet(info));
11799
11800                // This is a bundled system app so choose the path based on the ABI.
11801                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11802                // is just the default path.
11803                final String apkName = deriveCodePathName(codePath);
11804                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11805                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11806                        apkName).getAbsolutePath();
11807
11808                if (info.secondaryCpuAbi != null) {
11809                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11810                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11811                            secondaryLibDir, apkName).getAbsolutePath();
11812                }
11813            } else if (asecApp) {
11814                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11815                        .getAbsolutePath();
11816            } else {
11817                final String apkName = deriveCodePathName(codePath);
11818                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11819                        .getAbsolutePath();
11820            }
11821
11822            info.nativeLibraryRootRequiresIsa = false;
11823            info.nativeLibraryDir = info.nativeLibraryRootDir;
11824        } else {
11825            // Cluster install
11826            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11827            info.nativeLibraryRootRequiresIsa = true;
11828
11829            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11830                    getPrimaryInstructionSet(info)).getAbsolutePath();
11831
11832            if (info.secondaryCpuAbi != null) {
11833                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11834                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11835            }
11836        }
11837    }
11838
11839    /**
11840     * Calculate the abis and roots for a bundled app. These can uniquely
11841     * be determined from the contents of the system partition, i.e whether
11842     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11843     * of this information, and instead assume that the system was built
11844     * sensibly.
11845     */
11846    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11847                                           PackageSetting pkgSetting) {
11848        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11849
11850        // If "/system/lib64/apkname" exists, assume that is the per-package
11851        // native library directory to use; otherwise use "/system/lib/apkname".
11852        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11853        setBundledAppAbi(pkg, apkRoot, apkName);
11854        // pkgSetting might be null during rescan following uninstall of updates
11855        // to a bundled app, so accommodate that possibility.  The settings in
11856        // that case will be established later from the parsed package.
11857        //
11858        // If the settings aren't null, sync them up with what we've just derived.
11859        // note that apkRoot isn't stored in the package settings.
11860        if (pkgSetting != null) {
11861            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11862            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11863        }
11864    }
11865
11866    /**
11867     * Deduces the ABI of a bundled app and sets the relevant fields on the
11868     * parsed pkg object.
11869     *
11870     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11871     *        under which system libraries are installed.
11872     * @param apkName the name of the installed package.
11873     */
11874    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11875        final File codeFile = new File(pkg.codePath);
11876
11877        final boolean has64BitLibs;
11878        final boolean has32BitLibs;
11879        if (isApkFile(codeFile)) {
11880            // Monolithic install
11881            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11882            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11883        } else {
11884            // Cluster install
11885            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11886            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11887                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11888                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11889                has64BitLibs = (new File(rootDir, isa)).exists();
11890            } else {
11891                has64BitLibs = false;
11892            }
11893            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11894                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11895                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11896                has32BitLibs = (new File(rootDir, isa)).exists();
11897            } else {
11898                has32BitLibs = false;
11899            }
11900        }
11901
11902        if (has64BitLibs && !has32BitLibs) {
11903            // The package has 64 bit libs, but not 32 bit libs. Its primary
11904            // ABI should be 64 bit. We can safely assume here that the bundled
11905            // native libraries correspond to the most preferred ABI in the list.
11906
11907            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11908            pkg.applicationInfo.secondaryCpuAbi = null;
11909        } else if (has32BitLibs && !has64BitLibs) {
11910            // The package has 32 bit libs but not 64 bit libs. Its primary
11911            // ABI should be 32 bit.
11912
11913            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11914            pkg.applicationInfo.secondaryCpuAbi = null;
11915        } else if (has32BitLibs && has64BitLibs) {
11916            // The application has both 64 and 32 bit bundled libraries. We check
11917            // here that the app declares multiArch support, and warn if it doesn't.
11918            //
11919            // We will be lenient here and record both ABIs. The primary will be the
11920            // ABI that's higher on the list, i.e, a device that's configured to prefer
11921            // 64 bit apps will see a 64 bit primary ABI,
11922
11923            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11924                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11925            }
11926
11927            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11928                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11929                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11930            } else {
11931                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11932                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11933            }
11934        } else {
11935            pkg.applicationInfo.primaryCpuAbi = null;
11936            pkg.applicationInfo.secondaryCpuAbi = null;
11937        }
11938    }
11939
11940    private void killApplication(String pkgName, int appId, String reason) {
11941        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11942    }
11943
11944    private void killApplication(String pkgName, int appId, int userId, String reason) {
11945        // Request the ActivityManager to kill the process(only for existing packages)
11946        // so that we do not end up in a confused state while the user is still using the older
11947        // version of the application while the new one gets installed.
11948        final long token = Binder.clearCallingIdentity();
11949        try {
11950            IActivityManager am = ActivityManager.getService();
11951            if (am != null) {
11952                try {
11953                    am.killApplication(pkgName, appId, userId, reason);
11954                } catch (RemoteException e) {
11955                }
11956            }
11957        } finally {
11958            Binder.restoreCallingIdentity(token);
11959        }
11960    }
11961
11962    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11963        // Remove the parent package setting
11964        PackageSetting ps = (PackageSetting) pkg.mExtras;
11965        if (ps != null) {
11966            removePackageLI(ps, chatty);
11967        }
11968        // Remove the child package setting
11969        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11970        for (int i = 0; i < childCount; i++) {
11971            PackageParser.Package childPkg = pkg.childPackages.get(i);
11972            ps = (PackageSetting) childPkg.mExtras;
11973            if (ps != null) {
11974                removePackageLI(ps, chatty);
11975            }
11976        }
11977    }
11978
11979    void removePackageLI(PackageSetting ps, boolean chatty) {
11980        if (DEBUG_INSTALL) {
11981            if (chatty)
11982                Log.d(TAG, "Removing package " + ps.name);
11983        }
11984
11985        // writer
11986        synchronized (mPackages) {
11987            mPackages.remove(ps.name);
11988            final PackageParser.Package pkg = ps.pkg;
11989            if (pkg != null) {
11990                cleanPackageDataStructuresLILPw(pkg, chatty);
11991            }
11992        }
11993    }
11994
11995    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11996        if (DEBUG_INSTALL) {
11997            if (chatty)
11998                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11999        }
12000
12001        // writer
12002        synchronized (mPackages) {
12003            // Remove the parent package
12004            mPackages.remove(pkg.applicationInfo.packageName);
12005            cleanPackageDataStructuresLILPw(pkg, chatty);
12006
12007            // Remove the child packages
12008            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12009            for (int i = 0; i < childCount; i++) {
12010                PackageParser.Package childPkg = pkg.childPackages.get(i);
12011                mPackages.remove(childPkg.applicationInfo.packageName);
12012                cleanPackageDataStructuresLILPw(childPkg, chatty);
12013            }
12014        }
12015    }
12016
12017    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12018        int N = pkg.providers.size();
12019        StringBuilder r = null;
12020        int i;
12021        for (i=0; i<N; i++) {
12022            PackageParser.Provider p = pkg.providers.get(i);
12023            mProviders.removeProvider(p);
12024            if (p.info.authority == null) {
12025
12026                /* There was another ContentProvider with this authority when
12027                 * this app was installed so this authority is null,
12028                 * Ignore it as we don't have to unregister the provider.
12029                 */
12030                continue;
12031            }
12032            String names[] = p.info.authority.split(";");
12033            for (int j = 0; j < names.length; j++) {
12034                if (mProvidersByAuthority.get(names[j]) == p) {
12035                    mProvidersByAuthority.remove(names[j]);
12036                    if (DEBUG_REMOVE) {
12037                        if (chatty)
12038                            Log.d(TAG, "Unregistered content provider: " + names[j]
12039                                    + ", className = " + p.info.name + ", isSyncable = "
12040                                    + p.info.isSyncable);
12041                    }
12042                }
12043            }
12044            if (DEBUG_REMOVE && chatty) {
12045                if (r == null) {
12046                    r = new StringBuilder(256);
12047                } else {
12048                    r.append(' ');
12049                }
12050                r.append(p.info.name);
12051            }
12052        }
12053        if (r != null) {
12054            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12055        }
12056
12057        N = pkg.services.size();
12058        r = null;
12059        for (i=0; i<N; i++) {
12060            PackageParser.Service s = pkg.services.get(i);
12061            mServices.removeService(s);
12062            if (chatty) {
12063                if (r == null) {
12064                    r = new StringBuilder(256);
12065                } else {
12066                    r.append(' ');
12067                }
12068                r.append(s.info.name);
12069            }
12070        }
12071        if (r != null) {
12072            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12073        }
12074
12075        N = pkg.receivers.size();
12076        r = null;
12077        for (i=0; i<N; i++) {
12078            PackageParser.Activity a = pkg.receivers.get(i);
12079            mReceivers.removeActivity(a, "receiver");
12080            if (DEBUG_REMOVE && chatty) {
12081                if (r == null) {
12082                    r = new StringBuilder(256);
12083                } else {
12084                    r.append(' ');
12085                }
12086                r.append(a.info.name);
12087            }
12088        }
12089        if (r != null) {
12090            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12091        }
12092
12093        N = pkg.activities.size();
12094        r = null;
12095        for (i=0; i<N; i++) {
12096            PackageParser.Activity a = pkg.activities.get(i);
12097            mActivities.removeActivity(a, "activity");
12098            if (DEBUG_REMOVE && chatty) {
12099                if (r == null) {
12100                    r = new StringBuilder(256);
12101                } else {
12102                    r.append(' ');
12103                }
12104                r.append(a.info.name);
12105            }
12106        }
12107        if (r != null) {
12108            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12109        }
12110
12111        mPermissionManager.removeAllPermissions(pkg, chatty);
12112
12113        N = pkg.instrumentation.size();
12114        r = null;
12115        for (i=0; i<N; i++) {
12116            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12117            mInstrumentation.remove(a.getComponentName());
12118            if (DEBUG_REMOVE && chatty) {
12119                if (r == null) {
12120                    r = new StringBuilder(256);
12121                } else {
12122                    r.append(' ');
12123                }
12124                r.append(a.info.name);
12125            }
12126        }
12127        if (r != null) {
12128            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12129        }
12130
12131        r = null;
12132        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12133            // Only system apps can hold shared libraries.
12134            if (pkg.libraryNames != null) {
12135                for (i = 0; i < pkg.libraryNames.size(); i++) {
12136                    String name = pkg.libraryNames.get(i);
12137                    if (removeSharedLibraryLPw(name, 0)) {
12138                        if (DEBUG_REMOVE && chatty) {
12139                            if (r == null) {
12140                                r = new StringBuilder(256);
12141                            } else {
12142                                r.append(' ');
12143                            }
12144                            r.append(name);
12145                        }
12146                    }
12147                }
12148            }
12149        }
12150
12151        r = null;
12152
12153        // Any package can hold static shared libraries.
12154        if (pkg.staticSharedLibName != null) {
12155            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12156                if (DEBUG_REMOVE && chatty) {
12157                    if (r == null) {
12158                        r = new StringBuilder(256);
12159                    } else {
12160                        r.append(' ');
12161                    }
12162                    r.append(pkg.staticSharedLibName);
12163                }
12164            }
12165        }
12166
12167        if (r != null) {
12168            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12169        }
12170    }
12171
12172
12173    final class ActivityIntentResolver
12174            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12175        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12176                boolean defaultOnly, int userId) {
12177            if (!sUserManager.exists(userId)) return null;
12178            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12179            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12180        }
12181
12182        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12183                int userId) {
12184            if (!sUserManager.exists(userId)) return null;
12185            mFlags = flags;
12186            return super.queryIntent(intent, resolvedType,
12187                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12188                    userId);
12189        }
12190
12191        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12192                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12193            if (!sUserManager.exists(userId)) return null;
12194            if (packageActivities == null) {
12195                return null;
12196            }
12197            mFlags = flags;
12198            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12199            final int N = packageActivities.size();
12200            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12201                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12202
12203            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12204            for (int i = 0; i < N; ++i) {
12205                intentFilters = packageActivities.get(i).intents;
12206                if (intentFilters != null && intentFilters.size() > 0) {
12207                    PackageParser.ActivityIntentInfo[] array =
12208                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12209                    intentFilters.toArray(array);
12210                    listCut.add(array);
12211                }
12212            }
12213            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12214        }
12215
12216        /**
12217         * Finds a privileged activity that matches the specified activity names.
12218         */
12219        private PackageParser.Activity findMatchingActivity(
12220                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12221            for (PackageParser.Activity sysActivity : activityList) {
12222                if (sysActivity.info.name.equals(activityInfo.name)) {
12223                    return sysActivity;
12224                }
12225                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12226                    return sysActivity;
12227                }
12228                if (sysActivity.info.targetActivity != null) {
12229                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12230                        return sysActivity;
12231                    }
12232                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12233                        return sysActivity;
12234                    }
12235                }
12236            }
12237            return null;
12238        }
12239
12240        public class IterGenerator<E> {
12241            public Iterator<E> generate(ActivityIntentInfo info) {
12242                return null;
12243            }
12244        }
12245
12246        public class ActionIterGenerator extends IterGenerator<String> {
12247            @Override
12248            public Iterator<String> generate(ActivityIntentInfo info) {
12249                return info.actionsIterator();
12250            }
12251        }
12252
12253        public class CategoriesIterGenerator extends IterGenerator<String> {
12254            @Override
12255            public Iterator<String> generate(ActivityIntentInfo info) {
12256                return info.categoriesIterator();
12257            }
12258        }
12259
12260        public class SchemesIterGenerator extends IterGenerator<String> {
12261            @Override
12262            public Iterator<String> generate(ActivityIntentInfo info) {
12263                return info.schemesIterator();
12264            }
12265        }
12266
12267        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12268            @Override
12269            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12270                return info.authoritiesIterator();
12271            }
12272        }
12273
12274        /**
12275         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12276         * MODIFIED. Do not pass in a list that should not be changed.
12277         */
12278        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12279                IterGenerator<T> generator, Iterator<T> searchIterator) {
12280            // loop through the set of actions; every one must be found in the intent filter
12281            while (searchIterator.hasNext()) {
12282                // we must have at least one filter in the list to consider a match
12283                if (intentList.size() == 0) {
12284                    break;
12285                }
12286
12287                final T searchAction = searchIterator.next();
12288
12289                // loop through the set of intent filters
12290                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12291                while (intentIter.hasNext()) {
12292                    final ActivityIntentInfo intentInfo = intentIter.next();
12293                    boolean selectionFound = false;
12294
12295                    // loop through the intent filter's selection criteria; at least one
12296                    // of them must match the searched criteria
12297                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12298                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12299                        final T intentSelection = intentSelectionIter.next();
12300                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12301                            selectionFound = true;
12302                            break;
12303                        }
12304                    }
12305
12306                    // the selection criteria wasn't found in this filter's set; this filter
12307                    // is not a potential match
12308                    if (!selectionFound) {
12309                        intentIter.remove();
12310                    }
12311                }
12312            }
12313        }
12314
12315        private boolean isProtectedAction(ActivityIntentInfo filter) {
12316            final Iterator<String> actionsIter = filter.actionsIterator();
12317            while (actionsIter != null && actionsIter.hasNext()) {
12318                final String filterAction = actionsIter.next();
12319                if (PROTECTED_ACTIONS.contains(filterAction)) {
12320                    return true;
12321                }
12322            }
12323            return false;
12324        }
12325
12326        /**
12327         * Adjusts the priority of the given intent filter according to policy.
12328         * <p>
12329         * <ul>
12330         * <li>The priority for non privileged applications is capped to '0'</li>
12331         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12332         * <li>The priority for unbundled updates to privileged applications is capped to the
12333         *      priority defined on the system partition</li>
12334         * </ul>
12335         * <p>
12336         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12337         * allowed to obtain any priority on any action.
12338         */
12339        private void adjustPriority(
12340                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12341            // nothing to do; priority is fine as-is
12342            if (intent.getPriority() <= 0) {
12343                return;
12344            }
12345
12346            final ActivityInfo activityInfo = intent.activity.info;
12347            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12348
12349            final boolean privilegedApp =
12350                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12351            if (!privilegedApp) {
12352                // non-privileged applications can never define a priority >0
12353                if (DEBUG_FILTERS) {
12354                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12355                            + " package: " + applicationInfo.packageName
12356                            + " activity: " + intent.activity.className
12357                            + " origPrio: " + intent.getPriority());
12358                }
12359                intent.setPriority(0);
12360                return;
12361            }
12362
12363            if (systemActivities == null) {
12364                // the system package is not disabled; we're parsing the system partition
12365                if (isProtectedAction(intent)) {
12366                    if (mDeferProtectedFilters) {
12367                        // We can't deal with these just yet. No component should ever obtain a
12368                        // >0 priority for a protected actions, with ONE exception -- the setup
12369                        // wizard. The setup wizard, however, cannot be known until we're able to
12370                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12371                        // until all intent filters have been processed. Chicken, meet egg.
12372                        // Let the filter temporarily have a high priority and rectify the
12373                        // priorities after all system packages have been scanned.
12374                        mProtectedFilters.add(intent);
12375                        if (DEBUG_FILTERS) {
12376                            Slog.i(TAG, "Protected action; save for later;"
12377                                    + " package: " + applicationInfo.packageName
12378                                    + " activity: " + intent.activity.className
12379                                    + " origPrio: " + intent.getPriority());
12380                        }
12381                        return;
12382                    } else {
12383                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12384                            Slog.i(TAG, "No setup wizard;"
12385                                + " All protected intents capped to priority 0");
12386                        }
12387                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12388                            if (DEBUG_FILTERS) {
12389                                Slog.i(TAG, "Found setup wizard;"
12390                                    + " allow priority " + intent.getPriority() + ";"
12391                                    + " package: " + intent.activity.info.packageName
12392                                    + " activity: " + intent.activity.className
12393                                    + " priority: " + intent.getPriority());
12394                            }
12395                            // setup wizard gets whatever it wants
12396                            return;
12397                        }
12398                        if (DEBUG_FILTERS) {
12399                            Slog.i(TAG, "Protected action; cap priority to 0;"
12400                                    + " package: " + intent.activity.info.packageName
12401                                    + " activity: " + intent.activity.className
12402                                    + " origPrio: " + intent.getPriority());
12403                        }
12404                        intent.setPriority(0);
12405                        return;
12406                    }
12407                }
12408                // privileged apps on the system image get whatever priority they request
12409                return;
12410            }
12411
12412            // privileged app unbundled update ... try to find the same activity
12413            final PackageParser.Activity foundActivity =
12414                    findMatchingActivity(systemActivities, activityInfo);
12415            if (foundActivity == null) {
12416                // this is a new activity; it cannot obtain >0 priority
12417                if (DEBUG_FILTERS) {
12418                    Slog.i(TAG, "New activity; cap priority to 0;"
12419                            + " package: " + applicationInfo.packageName
12420                            + " activity: " + intent.activity.className
12421                            + " origPrio: " + intent.getPriority());
12422                }
12423                intent.setPriority(0);
12424                return;
12425            }
12426
12427            // found activity, now check for filter equivalence
12428
12429            // a shallow copy is enough; we modify the list, not its contents
12430            final List<ActivityIntentInfo> intentListCopy =
12431                    new ArrayList<>(foundActivity.intents);
12432            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12433
12434            // find matching action subsets
12435            final Iterator<String> actionsIterator = intent.actionsIterator();
12436            if (actionsIterator != null) {
12437                getIntentListSubset(
12438                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12439                if (intentListCopy.size() == 0) {
12440                    // no more intents to match; we're not equivalent
12441                    if (DEBUG_FILTERS) {
12442                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12443                                + " package: " + applicationInfo.packageName
12444                                + " activity: " + intent.activity.className
12445                                + " origPrio: " + intent.getPriority());
12446                    }
12447                    intent.setPriority(0);
12448                    return;
12449                }
12450            }
12451
12452            // find matching category subsets
12453            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12454            if (categoriesIterator != null) {
12455                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12456                        categoriesIterator);
12457                if (intentListCopy.size() == 0) {
12458                    // no more intents to match; we're not equivalent
12459                    if (DEBUG_FILTERS) {
12460                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12461                                + " package: " + applicationInfo.packageName
12462                                + " activity: " + intent.activity.className
12463                                + " origPrio: " + intent.getPriority());
12464                    }
12465                    intent.setPriority(0);
12466                    return;
12467                }
12468            }
12469
12470            // find matching schemes subsets
12471            final Iterator<String> schemesIterator = intent.schemesIterator();
12472            if (schemesIterator != null) {
12473                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12474                        schemesIterator);
12475                if (intentListCopy.size() == 0) {
12476                    // no more intents to match; we're not equivalent
12477                    if (DEBUG_FILTERS) {
12478                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12479                                + " package: " + applicationInfo.packageName
12480                                + " activity: " + intent.activity.className
12481                                + " origPrio: " + intent.getPriority());
12482                    }
12483                    intent.setPriority(0);
12484                    return;
12485                }
12486            }
12487
12488            // find matching authorities subsets
12489            final Iterator<IntentFilter.AuthorityEntry>
12490                    authoritiesIterator = intent.authoritiesIterator();
12491            if (authoritiesIterator != null) {
12492                getIntentListSubset(intentListCopy,
12493                        new AuthoritiesIterGenerator(),
12494                        authoritiesIterator);
12495                if (intentListCopy.size() == 0) {
12496                    // no more intents to match; we're not equivalent
12497                    if (DEBUG_FILTERS) {
12498                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12499                                + " package: " + applicationInfo.packageName
12500                                + " activity: " + intent.activity.className
12501                                + " origPrio: " + intent.getPriority());
12502                    }
12503                    intent.setPriority(0);
12504                    return;
12505                }
12506            }
12507
12508            // we found matching filter(s); app gets the max priority of all intents
12509            int cappedPriority = 0;
12510            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12511                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12512            }
12513            if (intent.getPriority() > cappedPriority) {
12514                if (DEBUG_FILTERS) {
12515                    Slog.i(TAG, "Found matching filter(s);"
12516                            + " cap priority to " + cappedPriority + ";"
12517                            + " package: " + applicationInfo.packageName
12518                            + " activity: " + intent.activity.className
12519                            + " origPrio: " + intent.getPriority());
12520                }
12521                intent.setPriority(cappedPriority);
12522                return;
12523            }
12524            // all this for nothing; the requested priority was <= what was on the system
12525        }
12526
12527        public final void addActivity(PackageParser.Activity a, String type) {
12528            mActivities.put(a.getComponentName(), a);
12529            if (DEBUG_SHOW_INFO)
12530                Log.v(
12531                TAG, "  " + type + " " +
12532                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12533            if (DEBUG_SHOW_INFO)
12534                Log.v(TAG, "    Class=" + a.info.name);
12535            final int NI = a.intents.size();
12536            for (int j=0; j<NI; j++) {
12537                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12538                if ("activity".equals(type)) {
12539                    final PackageSetting ps =
12540                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12541                    final List<PackageParser.Activity> systemActivities =
12542                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12543                    adjustPriority(systemActivities, intent);
12544                }
12545                if (DEBUG_SHOW_INFO) {
12546                    Log.v(TAG, "    IntentFilter:");
12547                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12548                }
12549                if (!intent.debugCheck()) {
12550                    Log.w(TAG, "==> For Activity " + a.info.name);
12551                }
12552                addFilter(intent);
12553            }
12554        }
12555
12556        public final void removeActivity(PackageParser.Activity a, String type) {
12557            mActivities.remove(a.getComponentName());
12558            if (DEBUG_SHOW_INFO) {
12559                Log.v(TAG, "  " + type + " "
12560                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12561                                : a.info.name) + ":");
12562                Log.v(TAG, "    Class=" + a.info.name);
12563            }
12564            final int NI = a.intents.size();
12565            for (int j=0; j<NI; j++) {
12566                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12567                if (DEBUG_SHOW_INFO) {
12568                    Log.v(TAG, "    IntentFilter:");
12569                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12570                }
12571                removeFilter(intent);
12572            }
12573        }
12574
12575        @Override
12576        protected boolean allowFilterResult(
12577                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12578            ActivityInfo filterAi = filter.activity.info;
12579            for (int i=dest.size()-1; i>=0; i--) {
12580                ActivityInfo destAi = dest.get(i).activityInfo;
12581                if (destAi.name == filterAi.name
12582                        && destAi.packageName == filterAi.packageName) {
12583                    return false;
12584                }
12585            }
12586            return true;
12587        }
12588
12589        @Override
12590        protected ActivityIntentInfo[] newArray(int size) {
12591            return new ActivityIntentInfo[size];
12592        }
12593
12594        @Override
12595        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12596            if (!sUserManager.exists(userId)) return true;
12597            PackageParser.Package p = filter.activity.owner;
12598            if (p != null) {
12599                PackageSetting ps = (PackageSetting)p.mExtras;
12600                if (ps != null) {
12601                    // System apps are never considered stopped for purposes of
12602                    // filtering, because there may be no way for the user to
12603                    // actually re-launch them.
12604                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12605                            && ps.getStopped(userId);
12606                }
12607            }
12608            return false;
12609        }
12610
12611        @Override
12612        protected boolean isPackageForFilter(String packageName,
12613                PackageParser.ActivityIntentInfo info) {
12614            return packageName.equals(info.activity.owner.packageName);
12615        }
12616
12617        @Override
12618        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12619                int match, int userId) {
12620            if (!sUserManager.exists(userId)) return null;
12621            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12622                return null;
12623            }
12624            final PackageParser.Activity activity = info.activity;
12625            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12626            if (ps == null) {
12627                return null;
12628            }
12629            final PackageUserState userState = ps.readUserState(userId);
12630            ActivityInfo ai =
12631                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12632            if (ai == null) {
12633                return null;
12634            }
12635            final boolean matchExplicitlyVisibleOnly =
12636                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12637            final boolean matchVisibleToInstantApp =
12638                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12639            final boolean componentVisible =
12640                    matchVisibleToInstantApp
12641                    && info.isVisibleToInstantApp()
12642                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12643            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12644            // throw out filters that aren't visible to ephemeral apps
12645            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12646                return null;
12647            }
12648            // throw out instant app filters if we're not explicitly requesting them
12649            if (!matchInstantApp && userState.instantApp) {
12650                return null;
12651            }
12652            // throw out instant app filters if updates are available; will trigger
12653            // instant app resolution
12654            if (userState.instantApp && ps.isUpdateAvailable()) {
12655                return null;
12656            }
12657            final ResolveInfo res = new ResolveInfo();
12658            res.activityInfo = ai;
12659            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12660                res.filter = info;
12661            }
12662            if (info != null) {
12663                res.handleAllWebDataURI = info.handleAllWebDataURI();
12664            }
12665            res.priority = info.getPriority();
12666            res.preferredOrder = activity.owner.mPreferredOrder;
12667            //System.out.println("Result: " + res.activityInfo.className +
12668            //                   " = " + res.priority);
12669            res.match = match;
12670            res.isDefault = info.hasDefault;
12671            res.labelRes = info.labelRes;
12672            res.nonLocalizedLabel = info.nonLocalizedLabel;
12673            if (userNeedsBadging(userId)) {
12674                res.noResourceId = true;
12675            } else {
12676                res.icon = info.icon;
12677            }
12678            res.iconResourceId = info.icon;
12679            res.system = res.activityInfo.applicationInfo.isSystemApp();
12680            res.isInstantAppAvailable = userState.instantApp;
12681            return res;
12682        }
12683
12684        @Override
12685        protected void sortResults(List<ResolveInfo> results) {
12686            Collections.sort(results, mResolvePrioritySorter);
12687        }
12688
12689        @Override
12690        protected void dumpFilter(PrintWriter out, String prefix,
12691                PackageParser.ActivityIntentInfo filter) {
12692            out.print(prefix); out.print(
12693                    Integer.toHexString(System.identityHashCode(filter.activity)));
12694                    out.print(' ');
12695                    filter.activity.printComponentShortName(out);
12696                    out.print(" filter ");
12697                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12698        }
12699
12700        @Override
12701        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12702            return filter.activity;
12703        }
12704
12705        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12706            PackageParser.Activity activity = (PackageParser.Activity)label;
12707            out.print(prefix); out.print(
12708                    Integer.toHexString(System.identityHashCode(activity)));
12709                    out.print(' ');
12710                    activity.printComponentShortName(out);
12711            if (count > 1) {
12712                out.print(" ("); out.print(count); out.print(" filters)");
12713            }
12714            out.println();
12715        }
12716
12717        // Keys are String (activity class name), values are Activity.
12718        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12719                = new ArrayMap<ComponentName, PackageParser.Activity>();
12720        private int mFlags;
12721    }
12722
12723    private final class ServiceIntentResolver
12724            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12725        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12726                boolean defaultOnly, int userId) {
12727            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12728            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12729        }
12730
12731        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12732                int userId) {
12733            if (!sUserManager.exists(userId)) return null;
12734            mFlags = flags;
12735            return super.queryIntent(intent, resolvedType,
12736                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12737                    userId);
12738        }
12739
12740        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12741                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12742            if (!sUserManager.exists(userId)) return null;
12743            if (packageServices == null) {
12744                return null;
12745            }
12746            mFlags = flags;
12747            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12748            final int N = packageServices.size();
12749            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12750                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12751
12752            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12753            for (int i = 0; i < N; ++i) {
12754                intentFilters = packageServices.get(i).intents;
12755                if (intentFilters != null && intentFilters.size() > 0) {
12756                    PackageParser.ServiceIntentInfo[] array =
12757                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12758                    intentFilters.toArray(array);
12759                    listCut.add(array);
12760                }
12761            }
12762            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12763        }
12764
12765        public final void addService(PackageParser.Service s) {
12766            mServices.put(s.getComponentName(), s);
12767            if (DEBUG_SHOW_INFO) {
12768                Log.v(TAG, "  "
12769                        + (s.info.nonLocalizedLabel != null
12770                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12771                Log.v(TAG, "    Class=" + s.info.name);
12772            }
12773            final int NI = s.intents.size();
12774            int j;
12775            for (j=0; j<NI; j++) {
12776                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12777                if (DEBUG_SHOW_INFO) {
12778                    Log.v(TAG, "    IntentFilter:");
12779                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12780                }
12781                if (!intent.debugCheck()) {
12782                    Log.w(TAG, "==> For Service " + s.info.name);
12783                }
12784                addFilter(intent);
12785            }
12786        }
12787
12788        public final void removeService(PackageParser.Service s) {
12789            mServices.remove(s.getComponentName());
12790            if (DEBUG_SHOW_INFO) {
12791                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12792                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12793                Log.v(TAG, "    Class=" + s.info.name);
12794            }
12795            final int NI = s.intents.size();
12796            int j;
12797            for (j=0; j<NI; j++) {
12798                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12799                if (DEBUG_SHOW_INFO) {
12800                    Log.v(TAG, "    IntentFilter:");
12801                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12802                }
12803                removeFilter(intent);
12804            }
12805        }
12806
12807        @Override
12808        protected boolean allowFilterResult(
12809                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12810            ServiceInfo filterSi = filter.service.info;
12811            for (int i=dest.size()-1; i>=0; i--) {
12812                ServiceInfo destAi = dest.get(i).serviceInfo;
12813                if (destAi.name == filterSi.name
12814                        && destAi.packageName == filterSi.packageName) {
12815                    return false;
12816                }
12817            }
12818            return true;
12819        }
12820
12821        @Override
12822        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12823            return new PackageParser.ServiceIntentInfo[size];
12824        }
12825
12826        @Override
12827        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12828            if (!sUserManager.exists(userId)) return true;
12829            PackageParser.Package p = filter.service.owner;
12830            if (p != null) {
12831                PackageSetting ps = (PackageSetting)p.mExtras;
12832                if (ps != null) {
12833                    // System apps are never considered stopped for purposes of
12834                    // filtering, because there may be no way for the user to
12835                    // actually re-launch them.
12836                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12837                            && ps.getStopped(userId);
12838                }
12839            }
12840            return false;
12841        }
12842
12843        @Override
12844        protected boolean isPackageForFilter(String packageName,
12845                PackageParser.ServiceIntentInfo info) {
12846            return packageName.equals(info.service.owner.packageName);
12847        }
12848
12849        @Override
12850        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12851                int match, int userId) {
12852            if (!sUserManager.exists(userId)) return null;
12853            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12854            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12855                return null;
12856            }
12857            final PackageParser.Service service = info.service;
12858            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12859            if (ps == null) {
12860                return null;
12861            }
12862            final PackageUserState userState = ps.readUserState(userId);
12863            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12864                    userState, userId);
12865            if (si == null) {
12866                return null;
12867            }
12868            final boolean matchVisibleToInstantApp =
12869                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12870            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12871            // throw out filters that aren't visible to ephemeral apps
12872            if (matchVisibleToInstantApp
12873                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12874                return null;
12875            }
12876            // throw out ephemeral filters if we're not explicitly requesting them
12877            if (!isInstantApp && userState.instantApp) {
12878                return null;
12879            }
12880            // throw out instant app filters if updates are available; will trigger
12881            // instant app resolution
12882            if (userState.instantApp && ps.isUpdateAvailable()) {
12883                return null;
12884            }
12885            final ResolveInfo res = new ResolveInfo();
12886            res.serviceInfo = si;
12887            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12888                res.filter = filter;
12889            }
12890            res.priority = info.getPriority();
12891            res.preferredOrder = service.owner.mPreferredOrder;
12892            res.match = match;
12893            res.isDefault = info.hasDefault;
12894            res.labelRes = info.labelRes;
12895            res.nonLocalizedLabel = info.nonLocalizedLabel;
12896            res.icon = info.icon;
12897            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12898            return res;
12899        }
12900
12901        @Override
12902        protected void sortResults(List<ResolveInfo> results) {
12903            Collections.sort(results, mResolvePrioritySorter);
12904        }
12905
12906        @Override
12907        protected void dumpFilter(PrintWriter out, String prefix,
12908                PackageParser.ServiceIntentInfo filter) {
12909            out.print(prefix); out.print(
12910                    Integer.toHexString(System.identityHashCode(filter.service)));
12911                    out.print(' ');
12912                    filter.service.printComponentShortName(out);
12913                    out.print(" filter ");
12914                    out.print(Integer.toHexString(System.identityHashCode(filter)));
12915                    if (filter.service.info.permission != null) {
12916                        out.print(" permission "); out.println(filter.service.info.permission);
12917                    } else {
12918                        out.println();
12919                    }
12920        }
12921
12922        @Override
12923        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12924            return filter.service;
12925        }
12926
12927        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12928            PackageParser.Service service = (PackageParser.Service)label;
12929            out.print(prefix); out.print(
12930                    Integer.toHexString(System.identityHashCode(service)));
12931                    out.print(' ');
12932                    service.printComponentShortName(out);
12933            if (count > 1) {
12934                out.print(" ("); out.print(count); out.print(" filters)");
12935            }
12936            out.println();
12937        }
12938
12939//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12940//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12941//            final List<ResolveInfo> retList = Lists.newArrayList();
12942//            while (i.hasNext()) {
12943//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12944//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12945//                    retList.add(resolveInfo);
12946//                }
12947//            }
12948//            return retList;
12949//        }
12950
12951        // Keys are String (activity class name), values are Activity.
12952        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12953                = new ArrayMap<ComponentName, PackageParser.Service>();
12954        private int mFlags;
12955    }
12956
12957    private final class ProviderIntentResolver
12958            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12959        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12960                boolean defaultOnly, int userId) {
12961            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12962            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12963        }
12964
12965        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12966                int userId) {
12967            if (!sUserManager.exists(userId))
12968                return null;
12969            mFlags = flags;
12970            return super.queryIntent(intent, resolvedType,
12971                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12972                    userId);
12973        }
12974
12975        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12976                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12977            if (!sUserManager.exists(userId))
12978                return null;
12979            if (packageProviders == null) {
12980                return null;
12981            }
12982            mFlags = flags;
12983            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12984            final int N = packageProviders.size();
12985            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12986                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12987
12988            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12989            for (int i = 0; i < N; ++i) {
12990                intentFilters = packageProviders.get(i).intents;
12991                if (intentFilters != null && intentFilters.size() > 0) {
12992                    PackageParser.ProviderIntentInfo[] array =
12993                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12994                    intentFilters.toArray(array);
12995                    listCut.add(array);
12996                }
12997            }
12998            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12999        }
13000
13001        public final void addProvider(PackageParser.Provider p) {
13002            if (mProviders.containsKey(p.getComponentName())) {
13003                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13004                return;
13005            }
13006
13007            mProviders.put(p.getComponentName(), p);
13008            if (DEBUG_SHOW_INFO) {
13009                Log.v(TAG, "  "
13010                        + (p.info.nonLocalizedLabel != null
13011                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13012                Log.v(TAG, "    Class=" + p.info.name);
13013            }
13014            final int NI = p.intents.size();
13015            int j;
13016            for (j = 0; j < NI; j++) {
13017                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13018                if (DEBUG_SHOW_INFO) {
13019                    Log.v(TAG, "    IntentFilter:");
13020                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13021                }
13022                if (!intent.debugCheck()) {
13023                    Log.w(TAG, "==> For Provider " + p.info.name);
13024                }
13025                addFilter(intent);
13026            }
13027        }
13028
13029        public final void removeProvider(PackageParser.Provider p) {
13030            mProviders.remove(p.getComponentName());
13031            if (DEBUG_SHOW_INFO) {
13032                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13033                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13034                Log.v(TAG, "    Class=" + p.info.name);
13035            }
13036            final int NI = p.intents.size();
13037            int j;
13038            for (j = 0; j < NI; j++) {
13039                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13040                if (DEBUG_SHOW_INFO) {
13041                    Log.v(TAG, "    IntentFilter:");
13042                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13043                }
13044                removeFilter(intent);
13045            }
13046        }
13047
13048        @Override
13049        protected boolean allowFilterResult(
13050                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13051            ProviderInfo filterPi = filter.provider.info;
13052            for (int i = dest.size() - 1; i >= 0; i--) {
13053                ProviderInfo destPi = dest.get(i).providerInfo;
13054                if (destPi.name == filterPi.name
13055                        && destPi.packageName == filterPi.packageName) {
13056                    return false;
13057                }
13058            }
13059            return true;
13060        }
13061
13062        @Override
13063        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13064            return new PackageParser.ProviderIntentInfo[size];
13065        }
13066
13067        @Override
13068        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13069            if (!sUserManager.exists(userId))
13070                return true;
13071            PackageParser.Package p = filter.provider.owner;
13072            if (p != null) {
13073                PackageSetting ps = (PackageSetting) p.mExtras;
13074                if (ps != null) {
13075                    // System apps are never considered stopped for purposes of
13076                    // filtering, because there may be no way for the user to
13077                    // actually re-launch them.
13078                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13079                            && ps.getStopped(userId);
13080                }
13081            }
13082            return false;
13083        }
13084
13085        @Override
13086        protected boolean isPackageForFilter(String packageName,
13087                PackageParser.ProviderIntentInfo info) {
13088            return packageName.equals(info.provider.owner.packageName);
13089        }
13090
13091        @Override
13092        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13093                int match, int userId) {
13094            if (!sUserManager.exists(userId))
13095                return null;
13096            final PackageParser.ProviderIntentInfo info = filter;
13097            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13098                return null;
13099            }
13100            final PackageParser.Provider provider = info.provider;
13101            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13102            if (ps == null) {
13103                return null;
13104            }
13105            final PackageUserState userState = ps.readUserState(userId);
13106            final boolean matchVisibleToInstantApp =
13107                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13108            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13109            // throw out filters that aren't visible to instant applications
13110            if (matchVisibleToInstantApp
13111                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13112                return null;
13113            }
13114            // throw out instant application filters if we're not explicitly requesting them
13115            if (!isInstantApp && userState.instantApp) {
13116                return null;
13117            }
13118            // throw out instant application filters if updates are available; will trigger
13119            // instant application resolution
13120            if (userState.instantApp && ps.isUpdateAvailable()) {
13121                return null;
13122            }
13123            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13124                    userState, userId);
13125            if (pi == null) {
13126                return null;
13127            }
13128            final ResolveInfo res = new ResolveInfo();
13129            res.providerInfo = pi;
13130            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13131                res.filter = filter;
13132            }
13133            res.priority = info.getPriority();
13134            res.preferredOrder = provider.owner.mPreferredOrder;
13135            res.match = match;
13136            res.isDefault = info.hasDefault;
13137            res.labelRes = info.labelRes;
13138            res.nonLocalizedLabel = info.nonLocalizedLabel;
13139            res.icon = info.icon;
13140            res.system = res.providerInfo.applicationInfo.isSystemApp();
13141            return res;
13142        }
13143
13144        @Override
13145        protected void sortResults(List<ResolveInfo> results) {
13146            Collections.sort(results, mResolvePrioritySorter);
13147        }
13148
13149        @Override
13150        protected void dumpFilter(PrintWriter out, String prefix,
13151                PackageParser.ProviderIntentInfo filter) {
13152            out.print(prefix);
13153            out.print(
13154                    Integer.toHexString(System.identityHashCode(filter.provider)));
13155            out.print(' ');
13156            filter.provider.printComponentShortName(out);
13157            out.print(" filter ");
13158            out.println(Integer.toHexString(System.identityHashCode(filter)));
13159        }
13160
13161        @Override
13162        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13163            return filter.provider;
13164        }
13165
13166        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13167            PackageParser.Provider provider = (PackageParser.Provider)label;
13168            out.print(prefix); out.print(
13169                    Integer.toHexString(System.identityHashCode(provider)));
13170                    out.print(' ');
13171                    provider.printComponentShortName(out);
13172            if (count > 1) {
13173                out.print(" ("); out.print(count); out.print(" filters)");
13174            }
13175            out.println();
13176        }
13177
13178        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13179                = new ArrayMap<ComponentName, PackageParser.Provider>();
13180        private int mFlags;
13181    }
13182
13183    static final class InstantAppIntentResolver
13184            extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter,
13185            AuxiliaryResolveInfo.AuxiliaryFilter> {
13186        /**
13187         * The result that has the highest defined order. Ordering applies on a
13188         * per-package basis. Mapping is from package name to Pair of order and
13189         * EphemeralResolveInfo.
13190         * <p>
13191         * NOTE: This is implemented as a field variable for convenience and efficiency.
13192         * By having a field variable, we're able to track filter ordering as soon as
13193         * a non-zero order is defined. Otherwise, multiple loops across the result set
13194         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13195         * this needs to be contained entirely within {@link #filterResults}.
13196         */
13197        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13198
13199        @Override
13200        protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) {
13201            return new AuxiliaryResolveInfo.AuxiliaryFilter[size];
13202        }
13203
13204        @Override
13205        protected boolean isPackageForFilter(String packageName,
13206                AuxiliaryResolveInfo.AuxiliaryFilter responseObj) {
13207            return true;
13208        }
13209
13210        @Override
13211        protected AuxiliaryResolveInfo.AuxiliaryFilter newResult(
13212                AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) {
13213            if (!sUserManager.exists(userId)) {
13214                return null;
13215            }
13216            final String packageName = responseObj.resolveInfo.getPackageName();
13217            final Integer order = responseObj.getOrder();
13218            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13219                    mOrderResult.get(packageName);
13220            // ordering is enabled and this item's order isn't high enough
13221            if (lastOrderResult != null && lastOrderResult.first >= order) {
13222                return null;
13223            }
13224            final InstantAppResolveInfo res = responseObj.resolveInfo;
13225            if (order > 0) {
13226                // non-zero order, enable ordering
13227                mOrderResult.put(packageName, new Pair<>(order, res));
13228            }
13229            return responseObj;
13230        }
13231
13232        @Override
13233        protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) {
13234            // only do work if ordering is enabled [most of the time it won't be]
13235            if (mOrderResult.size() == 0) {
13236                return;
13237            }
13238            int resultSize = results.size();
13239            for (int i = 0; i < resultSize; i++) {
13240                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13241                final String packageName = info.getPackageName();
13242                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13243                if (savedInfo == null) {
13244                    // package doesn't having ordering
13245                    continue;
13246                }
13247                if (savedInfo.second == info) {
13248                    // circled back to the highest ordered item; remove from order list
13249                    mOrderResult.remove(packageName);
13250                    if (mOrderResult.size() == 0) {
13251                        // no more ordered items
13252                        break;
13253                    }
13254                    continue;
13255                }
13256                // item has a worse order, remove it from the result list
13257                results.remove(i);
13258                resultSize--;
13259                i--;
13260            }
13261        }
13262    }
13263
13264    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13265            new Comparator<ResolveInfo>() {
13266        public int compare(ResolveInfo r1, ResolveInfo r2) {
13267            int v1 = r1.priority;
13268            int v2 = r2.priority;
13269            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13270            if (v1 != v2) {
13271                return (v1 > v2) ? -1 : 1;
13272            }
13273            v1 = r1.preferredOrder;
13274            v2 = r2.preferredOrder;
13275            if (v1 != v2) {
13276                return (v1 > v2) ? -1 : 1;
13277            }
13278            if (r1.isDefault != r2.isDefault) {
13279                return r1.isDefault ? -1 : 1;
13280            }
13281            v1 = r1.match;
13282            v2 = r2.match;
13283            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13284            if (v1 != v2) {
13285                return (v1 > v2) ? -1 : 1;
13286            }
13287            if (r1.system != r2.system) {
13288                return r1.system ? -1 : 1;
13289            }
13290            if (r1.activityInfo != null) {
13291                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13292            }
13293            if (r1.serviceInfo != null) {
13294                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13295            }
13296            if (r1.providerInfo != null) {
13297                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13298            }
13299            return 0;
13300        }
13301    };
13302
13303    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13304            new Comparator<ProviderInfo>() {
13305        public int compare(ProviderInfo p1, ProviderInfo p2) {
13306            final int v1 = p1.initOrder;
13307            final int v2 = p2.initOrder;
13308            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13309        }
13310    };
13311
13312    @Override
13313    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13314            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13315            final int[] userIds, int[] instantUserIds) {
13316        mHandler.post(new Runnable() {
13317            @Override
13318            public void run() {
13319                try {
13320                    final IActivityManager am = ActivityManager.getService();
13321                    if (am == null) return;
13322                    final int[] resolvedUserIds;
13323                    if (userIds == null) {
13324                        resolvedUserIds = am.getRunningUserIds();
13325                    } else {
13326                        resolvedUserIds = userIds;
13327                    }
13328                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13329                            resolvedUserIds, false);
13330                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
13331                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13332                                instantUserIds, true);
13333                    }
13334                } catch (RemoteException ex) {
13335                }
13336            }
13337        });
13338    }
13339
13340    @Override
13341    public void notifyPackageAdded(String packageName) {
13342        final PackageListObserver[] observers;
13343        synchronized (mPackages) {
13344            if (mPackageListObservers.size() == 0) {
13345                return;
13346            }
13347            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13348        }
13349        for (int i = observers.length - 1; i >= 0; --i) {
13350            observers[i].onPackageAdded(packageName);
13351        }
13352    }
13353
13354    @Override
13355    public void notifyPackageRemoved(String packageName) {
13356        final PackageListObserver[] observers;
13357        synchronized (mPackages) {
13358            if (mPackageListObservers.size() == 0) {
13359                return;
13360            }
13361            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13362        }
13363        for (int i = observers.length - 1; i >= 0; --i) {
13364            observers[i].onPackageRemoved(packageName);
13365        }
13366    }
13367
13368    /**
13369     * Sends a broadcast for the given action.
13370     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13371     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13372     * the system and applications allowed to see instant applications to receive package
13373     * lifecycle events for instant applications.
13374     */
13375    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13376            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13377            int[] userIds, boolean isInstantApp)
13378                    throws RemoteException {
13379        for (int id : userIds) {
13380            final Intent intent = new Intent(action,
13381                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13382            final String[] requiredPermissions =
13383                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13384            if (extras != null) {
13385                intent.putExtras(extras);
13386            }
13387            if (targetPkg != null) {
13388                intent.setPackage(targetPkg);
13389            }
13390            // Modify the UID when posting to other users
13391            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13392            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13393                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13394                intent.putExtra(Intent.EXTRA_UID, uid);
13395            }
13396            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13397            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13398            if (DEBUG_BROADCASTS) {
13399                RuntimeException here = new RuntimeException("here");
13400                here.fillInStackTrace();
13401                Slog.d(TAG, "Sending to user " + id + ": "
13402                        + intent.toShortString(false, true, false, false)
13403                        + " " + intent.getExtras(), here);
13404            }
13405            am.broadcastIntent(null, intent, null, finishedReceiver,
13406                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13407                    null, finishedReceiver != null, false, id);
13408        }
13409    }
13410
13411    /**
13412     * Check if the external storage media is available. This is true if there
13413     * is a mounted external storage medium or if the external storage is
13414     * emulated.
13415     */
13416    private boolean isExternalMediaAvailable() {
13417        return mMediaMounted || Environment.isExternalStorageEmulated();
13418    }
13419
13420    @Override
13421    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13422        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13423            return null;
13424        }
13425        if (!isExternalMediaAvailable()) {
13426                // If the external storage is no longer mounted at this point,
13427                // the caller may not have been able to delete all of this
13428                // packages files and can not delete any more.  Bail.
13429            return null;
13430        }
13431        synchronized (mPackages) {
13432            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13433            if (lastPackage != null) {
13434                pkgs.remove(lastPackage);
13435            }
13436            if (pkgs.size() > 0) {
13437                return pkgs.get(0);
13438            }
13439        }
13440        return null;
13441    }
13442
13443    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13444        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13445                userId, andCode ? 1 : 0, packageName);
13446        if (mSystemReady) {
13447            msg.sendToTarget();
13448        } else {
13449            if (mPostSystemReadyMessages == null) {
13450                mPostSystemReadyMessages = new ArrayList<>();
13451            }
13452            mPostSystemReadyMessages.add(msg);
13453        }
13454    }
13455
13456    void startCleaningPackages() {
13457        // reader
13458        if (!isExternalMediaAvailable()) {
13459            return;
13460        }
13461        synchronized (mPackages) {
13462            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13463                return;
13464            }
13465        }
13466        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13467        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13468        IActivityManager am = ActivityManager.getService();
13469        if (am != null) {
13470            int dcsUid = -1;
13471            synchronized (mPackages) {
13472                if (!mDefaultContainerWhitelisted) {
13473                    mDefaultContainerWhitelisted = true;
13474                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13475                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13476                }
13477            }
13478            try {
13479                if (dcsUid > 0) {
13480                    am.backgroundWhitelistUid(dcsUid);
13481                }
13482                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13483                        UserHandle.USER_SYSTEM);
13484            } catch (RemoteException e) {
13485            }
13486        }
13487    }
13488
13489    /**
13490     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13491     * it is acting on behalf on an enterprise or the user).
13492     *
13493     * Note that the ordering of the conditionals in this method is important. The checks we perform
13494     * are as follows, in this order:
13495     *
13496     * 1) If the install is being performed by a system app, we can trust the app to have set the
13497     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13498     *    what it is.
13499     * 2) If the install is being performed by a device or profile owner app, the install reason
13500     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13501     *    set the install reason correctly. If the app targets an older SDK version where install
13502     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13503     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13504     * 3) In all other cases, the install is being performed by a regular app that is neither part
13505     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13506     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13507     *    set to enterprise policy and if so, change it to unknown instead.
13508     */
13509    private int fixUpInstallReason(String installerPackageName, int installerUid,
13510            int installReason) {
13511        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13512                == PERMISSION_GRANTED) {
13513            // If the install is being performed by a system app, we trust that app to have set the
13514            // install reason correctly.
13515            return installReason;
13516        }
13517
13518        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13519            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13520        if (dpm != null) {
13521            ComponentName owner = null;
13522            try {
13523                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13524                if (owner == null) {
13525                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13526                }
13527            } catch (RemoteException e) {
13528            }
13529            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13530                // If the install is being performed by a device or profile owner, the install
13531                // reason should be enterprise policy.
13532                return PackageManager.INSTALL_REASON_POLICY;
13533            }
13534        }
13535
13536        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13537            // If the install is being performed by a regular app (i.e. neither system app nor
13538            // device or profile owner), we have no reason to believe that the app is acting on
13539            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13540            // change it to unknown instead.
13541            return PackageManager.INSTALL_REASON_UNKNOWN;
13542        }
13543
13544        // If the install is being performed by a regular app and the install reason was set to any
13545        // value but enterprise policy, leave the install reason unchanged.
13546        return installReason;
13547    }
13548
13549    void installStage(String packageName, File stagedDir,
13550            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13551            String installerPackageName, int installerUid, UserHandle user,
13552            PackageParser.SigningDetails signingDetails) {
13553        if (DEBUG_INSTANT) {
13554            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13555                Slog.d(TAG, "Ephemeral install of " + packageName);
13556            }
13557        }
13558        final VerificationInfo verificationInfo = new VerificationInfo(
13559                sessionParams.originatingUri, sessionParams.referrerUri,
13560                sessionParams.originatingUid, installerUid);
13561
13562        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13563
13564        final Message msg = mHandler.obtainMessage(INIT_COPY);
13565        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13566                sessionParams.installReason);
13567        final InstallParams params = new InstallParams(origin, null, observer,
13568                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13569                verificationInfo, user, sessionParams.abiOverride,
13570                sessionParams.grantedRuntimePermissions, signingDetails, installReason);
13571        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13572        msg.obj = params;
13573
13574        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13575                System.identityHashCode(msg.obj));
13576        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13577                System.identityHashCode(msg.obj));
13578
13579        mHandler.sendMessage(msg);
13580    }
13581
13582    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13583            int userId) {
13584        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13585        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13586        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13587        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13588        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13589                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13590
13591        // Send a session commit broadcast
13592        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13593        info.installReason = pkgSetting.getInstallReason(userId);
13594        info.appPackageName = packageName;
13595        sendSessionCommitBroadcast(info, userId);
13596    }
13597
13598    @Override
13599    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13600            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13601        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13602            return;
13603        }
13604        Bundle extras = new Bundle(1);
13605        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13606        final int uid = UserHandle.getUid(
13607                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13608        extras.putInt(Intent.EXTRA_UID, uid);
13609
13610        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13611                packageName, extras, 0, null, null, userIds, instantUserIds);
13612        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13613            mHandler.post(() -> {
13614                        for (int userId : userIds) {
13615                            sendBootCompletedBroadcastToSystemApp(
13616                                    packageName, includeStopped, userId);
13617                        }
13618                    }
13619            );
13620        }
13621    }
13622
13623    /**
13624     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13625     * automatically without needing an explicit launch.
13626     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13627     */
13628    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13629            int userId) {
13630        // If user is not running, the app didn't miss any broadcast
13631        if (!mUserManagerInternal.isUserRunning(userId)) {
13632            return;
13633        }
13634        final IActivityManager am = ActivityManager.getService();
13635        try {
13636            // Deliver LOCKED_BOOT_COMPLETED first
13637            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13638                    .setPackage(packageName);
13639            if (includeStopped) {
13640                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13641            }
13642            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13643            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13644                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13645
13646            // Deliver BOOT_COMPLETED only if user is unlocked
13647            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13648                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13649                if (includeStopped) {
13650                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13651                }
13652                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13653                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13654            }
13655        } catch (RemoteException e) {
13656            throw e.rethrowFromSystemServer();
13657        }
13658    }
13659
13660    @Override
13661    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13662            int userId) {
13663        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13664        PackageSetting pkgSetting;
13665        final int callingUid = Binder.getCallingUid();
13666        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13667                true /* requireFullPermission */, true /* checkShell */,
13668                "setApplicationHiddenSetting for user " + userId);
13669
13670        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13671            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13672            return false;
13673        }
13674
13675        long callingId = Binder.clearCallingIdentity();
13676        try {
13677            boolean sendAdded = false;
13678            boolean sendRemoved = false;
13679            // writer
13680            synchronized (mPackages) {
13681                pkgSetting = mSettings.mPackages.get(packageName);
13682                if (pkgSetting == null) {
13683                    return false;
13684                }
13685                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13686                    return false;
13687                }
13688                // Do not allow "android" is being disabled
13689                if ("android".equals(packageName)) {
13690                    Slog.w(TAG, "Cannot hide package: android");
13691                    return false;
13692                }
13693                // Cannot hide static shared libs as they are considered
13694                // a part of the using app (emulating static linking). Also
13695                // static libs are installed always on internal storage.
13696                PackageParser.Package pkg = mPackages.get(packageName);
13697                if (pkg != null && pkg.staticSharedLibName != null) {
13698                    Slog.w(TAG, "Cannot hide package: " + packageName
13699                            + " providing static shared library: "
13700                            + pkg.staticSharedLibName);
13701                    return false;
13702                }
13703                // Only allow protected packages to hide themselves.
13704                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13705                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13706                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13707                    return false;
13708                }
13709
13710                if (pkgSetting.getHidden(userId) != hidden) {
13711                    pkgSetting.setHidden(hidden, userId);
13712                    mSettings.writePackageRestrictionsLPr(userId);
13713                    if (hidden) {
13714                        sendRemoved = true;
13715                    } else {
13716                        sendAdded = true;
13717                    }
13718                }
13719            }
13720            if (sendAdded) {
13721                sendPackageAddedForUser(packageName, pkgSetting, userId);
13722                return true;
13723            }
13724            if (sendRemoved) {
13725                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13726                        "hiding pkg");
13727                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13728                return true;
13729            }
13730        } finally {
13731            Binder.restoreCallingIdentity(callingId);
13732        }
13733        return false;
13734    }
13735
13736    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13737            int userId) {
13738        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13739        info.removedPackage = packageName;
13740        info.installerPackageName = pkgSetting.installerPackageName;
13741        info.removedUsers = new int[] {userId};
13742        info.broadcastUsers = new int[] {userId};
13743        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13744        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13745    }
13746
13747    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13748        if (pkgList.length > 0) {
13749            Bundle extras = new Bundle(1);
13750            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13751
13752            sendPackageBroadcast(
13753                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13754                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13755                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13756                    new int[] {userId}, null);
13757        }
13758    }
13759
13760    /**
13761     * Returns true if application is not found or there was an error. Otherwise it returns
13762     * the hidden state of the package for the given user.
13763     */
13764    @Override
13765    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13766        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13767        final int callingUid = Binder.getCallingUid();
13768        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13769                true /* requireFullPermission */, false /* checkShell */,
13770                "getApplicationHidden for user " + userId);
13771        PackageSetting ps;
13772        long callingId = Binder.clearCallingIdentity();
13773        try {
13774            // writer
13775            synchronized (mPackages) {
13776                ps = mSettings.mPackages.get(packageName);
13777                if (ps == null) {
13778                    return true;
13779                }
13780                if (filterAppAccessLPr(ps, callingUid, userId)) {
13781                    return true;
13782                }
13783                return ps.getHidden(userId);
13784            }
13785        } finally {
13786            Binder.restoreCallingIdentity(callingId);
13787        }
13788    }
13789
13790    /**
13791     * @hide
13792     */
13793    @Override
13794    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13795            int installReason) {
13796        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13797                null);
13798        PackageSetting pkgSetting;
13799        final int callingUid = Binder.getCallingUid();
13800        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13801                true /* requireFullPermission */, true /* checkShell */,
13802                "installExistingPackage for user " + userId);
13803        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13804            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13805        }
13806
13807        long callingId = Binder.clearCallingIdentity();
13808        try {
13809            boolean installed = false;
13810            final boolean instantApp =
13811                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13812            final boolean fullApp =
13813                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13814
13815            // writer
13816            synchronized (mPackages) {
13817                pkgSetting = mSettings.mPackages.get(packageName);
13818                if (pkgSetting == null) {
13819                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13820                }
13821                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13822                    // only allow the existing package to be used if it's installed as a full
13823                    // application for at least one user
13824                    boolean installAllowed = false;
13825                    for (int checkUserId : sUserManager.getUserIds()) {
13826                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13827                        if (installAllowed) {
13828                            break;
13829                        }
13830                    }
13831                    if (!installAllowed) {
13832                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13833                    }
13834                }
13835                if (!pkgSetting.getInstalled(userId)) {
13836                    pkgSetting.setInstalled(true, userId);
13837                    pkgSetting.setHidden(false, userId);
13838                    pkgSetting.setInstallReason(installReason, userId);
13839                    mSettings.writePackageRestrictionsLPr(userId);
13840                    mSettings.writeKernelMappingLPr(pkgSetting);
13841                    installed = true;
13842                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13843                    // upgrade app from instant to full; we don't allow app downgrade
13844                    installed = true;
13845                }
13846                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13847            }
13848
13849            if (installed) {
13850                if (pkgSetting.pkg != null) {
13851                    synchronized (mInstallLock) {
13852                        // We don't need to freeze for a brand new install
13853                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13854                    }
13855                }
13856                sendPackageAddedForUser(packageName, pkgSetting, userId);
13857                synchronized (mPackages) {
13858                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13859                }
13860            }
13861        } finally {
13862            Binder.restoreCallingIdentity(callingId);
13863        }
13864
13865        return PackageManager.INSTALL_SUCCEEDED;
13866    }
13867
13868    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13869            boolean instantApp, boolean fullApp) {
13870        // no state specified; do nothing
13871        if (!instantApp && !fullApp) {
13872            return;
13873        }
13874        if (userId != UserHandle.USER_ALL) {
13875            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13876                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13877            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13878                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13879            }
13880        } else {
13881            for (int currentUserId : sUserManager.getUserIds()) {
13882                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13883                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13884                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13885                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13886                }
13887            }
13888        }
13889    }
13890
13891    boolean isUserRestricted(int userId, String restrictionKey) {
13892        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13893        if (restrictions.getBoolean(restrictionKey, false)) {
13894            Log.w(TAG, "User is restricted: " + restrictionKey);
13895            return true;
13896        }
13897        return false;
13898    }
13899
13900    @Override
13901    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13902            int userId) {
13903        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13904        final int callingUid = Binder.getCallingUid();
13905        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13906                true /* requireFullPermission */, true /* checkShell */,
13907                "setPackagesSuspended for user " + userId);
13908
13909        if (ArrayUtils.isEmpty(packageNames)) {
13910            return packageNames;
13911        }
13912
13913        // List of package names for whom the suspended state has changed.
13914        List<String> changedPackages = new ArrayList<>(packageNames.length);
13915        // List of package names for whom the suspended state is not set as requested in this
13916        // method.
13917        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13918        long callingId = Binder.clearCallingIdentity();
13919        try {
13920            for (int i = 0; i < packageNames.length; i++) {
13921                String packageName = packageNames[i];
13922                boolean changed = false;
13923                final int appId;
13924                synchronized (mPackages) {
13925                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13926                    if (pkgSetting == null
13927                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13928                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13929                                + "\". Skipping suspending/un-suspending.");
13930                        unactionedPackages.add(packageName);
13931                        continue;
13932                    }
13933                    appId = pkgSetting.appId;
13934                    if (pkgSetting.getSuspended(userId) != suspended) {
13935                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13936                            unactionedPackages.add(packageName);
13937                            continue;
13938                        }
13939                        pkgSetting.setSuspended(suspended, userId);
13940                        mSettings.writePackageRestrictionsLPr(userId);
13941                        changed = true;
13942                        changedPackages.add(packageName);
13943                    }
13944                }
13945
13946                if (changed && suspended) {
13947                    killApplication(packageName, UserHandle.getUid(userId, appId),
13948                            "suspending package");
13949                }
13950            }
13951        } finally {
13952            Binder.restoreCallingIdentity(callingId);
13953        }
13954
13955        if (!changedPackages.isEmpty()) {
13956            sendPackagesSuspendedForUser(changedPackages.toArray(
13957                    new String[changedPackages.size()]), userId, suspended);
13958        }
13959
13960        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13961    }
13962
13963    @Override
13964    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13965        final int callingUid = Binder.getCallingUid();
13966        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13967                true /* requireFullPermission */, false /* checkShell */,
13968                "isPackageSuspendedForUser for user " + userId);
13969        synchronized (mPackages) {
13970            final PackageSetting ps = mSettings.mPackages.get(packageName);
13971            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
13972                throw new IllegalArgumentException("Unknown target package: " + packageName);
13973            }
13974            return ps.getSuspended(userId);
13975        }
13976    }
13977
13978    @GuardedBy("mPackages")
13979    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13980        if (isPackageDeviceAdmin(packageName, userId)) {
13981            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13982                    + "\": has an active device admin");
13983            return false;
13984        }
13985
13986        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13987        if (packageName.equals(activeLauncherPackageName)) {
13988            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13989                    + "\": contains the active launcher");
13990            return false;
13991        }
13992
13993        if (packageName.equals(mRequiredInstallerPackage)) {
13994            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13995                    + "\": required for package installation");
13996            return false;
13997        }
13998
13999        if (packageName.equals(mRequiredUninstallerPackage)) {
14000            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14001                    + "\": required for package uninstallation");
14002            return false;
14003        }
14004
14005        if (packageName.equals(mRequiredVerifierPackage)) {
14006            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14007                    + "\": required for package verification");
14008            return false;
14009        }
14010
14011        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14012            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14013                    + "\": is the default dialer");
14014            return false;
14015        }
14016
14017        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14018            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14019                    + "\": protected package");
14020            return false;
14021        }
14022
14023        // Cannot suspend static shared libs as they are considered
14024        // a part of the using app (emulating static linking). Also
14025        // static libs are installed always on internal storage.
14026        PackageParser.Package pkg = mPackages.get(packageName);
14027        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14028            Slog.w(TAG, "Cannot suspend package: " + packageName
14029                    + " providing static shared library: "
14030                    + pkg.staticSharedLibName);
14031            return false;
14032        }
14033
14034        return true;
14035    }
14036
14037    private String getActiveLauncherPackageName(int userId) {
14038        Intent intent = new Intent(Intent.ACTION_MAIN);
14039        intent.addCategory(Intent.CATEGORY_HOME);
14040        ResolveInfo resolveInfo = resolveIntent(
14041                intent,
14042                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14043                PackageManager.MATCH_DEFAULT_ONLY,
14044                userId);
14045
14046        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14047    }
14048
14049    private String getDefaultDialerPackageName(int userId) {
14050        synchronized (mPackages) {
14051            return mSettings.getDefaultDialerPackageNameLPw(userId);
14052        }
14053    }
14054
14055    @Override
14056    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14057        mContext.enforceCallingOrSelfPermission(
14058                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14059                "Only package verification agents can verify applications");
14060
14061        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14062        final PackageVerificationResponse response = new PackageVerificationResponse(
14063                verificationCode, Binder.getCallingUid());
14064        msg.arg1 = id;
14065        msg.obj = response;
14066        mHandler.sendMessage(msg);
14067    }
14068
14069    @Override
14070    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14071            long millisecondsToDelay) {
14072        mContext.enforceCallingOrSelfPermission(
14073                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14074                "Only package verification agents can extend verification timeouts");
14075
14076        final PackageVerificationState state = mPendingVerification.get(id);
14077        final PackageVerificationResponse response = new PackageVerificationResponse(
14078                verificationCodeAtTimeout, Binder.getCallingUid());
14079
14080        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14081            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14082        }
14083        if (millisecondsToDelay < 0) {
14084            millisecondsToDelay = 0;
14085        }
14086        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14087                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14088            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14089        }
14090
14091        if ((state != null) && !state.timeoutExtended()) {
14092            state.extendTimeout();
14093
14094            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14095            msg.arg1 = id;
14096            msg.obj = response;
14097            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14098        }
14099    }
14100
14101    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14102            int verificationCode, UserHandle user) {
14103        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14104        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14105        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14106        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14107        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14108
14109        mContext.sendBroadcastAsUser(intent, user,
14110                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14111    }
14112
14113    private ComponentName matchComponentForVerifier(String packageName,
14114            List<ResolveInfo> receivers) {
14115        ActivityInfo targetReceiver = null;
14116
14117        final int NR = receivers.size();
14118        for (int i = 0; i < NR; i++) {
14119            final ResolveInfo info = receivers.get(i);
14120            if (info.activityInfo == null) {
14121                continue;
14122            }
14123
14124            if (packageName.equals(info.activityInfo.packageName)) {
14125                targetReceiver = info.activityInfo;
14126                break;
14127            }
14128        }
14129
14130        if (targetReceiver == null) {
14131            return null;
14132        }
14133
14134        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14135    }
14136
14137    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14138            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14139        if (pkgInfo.verifiers.length == 0) {
14140            return null;
14141        }
14142
14143        final int N = pkgInfo.verifiers.length;
14144        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14145        for (int i = 0; i < N; i++) {
14146            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14147
14148            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14149                    receivers);
14150            if (comp == null) {
14151                continue;
14152            }
14153
14154            final int verifierUid = getUidForVerifier(verifierInfo);
14155            if (verifierUid == -1) {
14156                continue;
14157            }
14158
14159            if (DEBUG_VERIFY) {
14160                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14161                        + " with the correct signature");
14162            }
14163            sufficientVerifiers.add(comp);
14164            verificationState.addSufficientVerifier(verifierUid);
14165        }
14166
14167        return sufficientVerifiers;
14168    }
14169
14170    private int getUidForVerifier(VerifierInfo verifierInfo) {
14171        synchronized (mPackages) {
14172            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14173            if (pkg == null) {
14174                return -1;
14175            } else if (pkg.mSigningDetails.signatures.length != 1) {
14176                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14177                        + " has more than one signature; ignoring");
14178                return -1;
14179            }
14180
14181            /*
14182             * If the public key of the package's signature does not match
14183             * our expected public key, then this is a different package and
14184             * we should skip.
14185             */
14186
14187            final byte[] expectedPublicKey;
14188            try {
14189                final Signature verifierSig = pkg.mSigningDetails.signatures[0];
14190                final PublicKey publicKey = verifierSig.getPublicKey();
14191                expectedPublicKey = publicKey.getEncoded();
14192            } catch (CertificateException e) {
14193                return -1;
14194            }
14195
14196            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14197
14198            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14199                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14200                        + " does not have the expected public key; ignoring");
14201                return -1;
14202            }
14203
14204            return pkg.applicationInfo.uid;
14205        }
14206    }
14207
14208    @Override
14209    public void finishPackageInstall(int token, boolean didLaunch) {
14210        enforceSystemOrRoot("Only the system is allowed to finish installs");
14211
14212        if (DEBUG_INSTALL) {
14213            Slog.v(TAG, "BM finishing package install for " + token);
14214        }
14215        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14216
14217        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14218        mHandler.sendMessage(msg);
14219    }
14220
14221    /**
14222     * Get the verification agent timeout.  Used for both the APK verifier and the
14223     * intent filter verifier.
14224     *
14225     * @return verification timeout in milliseconds
14226     */
14227    private long getVerificationTimeout() {
14228        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14229                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14230                DEFAULT_VERIFICATION_TIMEOUT);
14231    }
14232
14233    /**
14234     * Get the default verification agent response code.
14235     *
14236     * @return default verification response code
14237     */
14238    private int getDefaultVerificationResponse(UserHandle user) {
14239        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14240            return PackageManager.VERIFICATION_REJECT;
14241        }
14242        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14243                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14244                DEFAULT_VERIFICATION_RESPONSE);
14245    }
14246
14247    /**
14248     * Check whether or not package verification has been enabled.
14249     *
14250     * @return true if verification should be performed
14251     */
14252    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14253        if (!DEFAULT_VERIFY_ENABLE) {
14254            return false;
14255        }
14256
14257        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14258
14259        // Check if installing from ADB
14260        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14261            // Do not run verification in a test harness environment
14262            if (ActivityManager.isRunningInTestHarness()) {
14263                return false;
14264            }
14265            if (ensureVerifyAppsEnabled) {
14266                return true;
14267            }
14268            // Check if the developer does not want package verification for ADB installs
14269            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14270                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14271                return false;
14272            }
14273        } else {
14274            // only when not installed from ADB, skip verification for instant apps when
14275            // the installer and verifier are the same.
14276            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14277                if (mInstantAppInstallerActivity != null
14278                        && mInstantAppInstallerActivity.packageName.equals(
14279                                mRequiredVerifierPackage)) {
14280                    try {
14281                        mContext.getSystemService(AppOpsManager.class)
14282                                .checkPackage(installerUid, mRequiredVerifierPackage);
14283                        if (DEBUG_VERIFY) {
14284                            Slog.i(TAG, "disable verification for instant app");
14285                        }
14286                        return false;
14287                    } catch (SecurityException ignore) { }
14288                }
14289            }
14290        }
14291
14292        if (ensureVerifyAppsEnabled) {
14293            return true;
14294        }
14295
14296        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14297                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14298    }
14299
14300    @Override
14301    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14302            throws RemoteException {
14303        mContext.enforceCallingOrSelfPermission(
14304                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14305                "Only intentfilter verification agents can verify applications");
14306
14307        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14308        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14309                Binder.getCallingUid(), verificationCode, failedDomains);
14310        msg.arg1 = id;
14311        msg.obj = response;
14312        mHandler.sendMessage(msg);
14313    }
14314
14315    @Override
14316    public int getIntentVerificationStatus(String packageName, int userId) {
14317        final int callingUid = Binder.getCallingUid();
14318        if (UserHandle.getUserId(callingUid) != userId) {
14319            mContext.enforceCallingOrSelfPermission(
14320                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14321                    "getIntentVerificationStatus" + userId);
14322        }
14323        if (getInstantAppPackageName(callingUid) != null) {
14324            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14325        }
14326        synchronized (mPackages) {
14327            final PackageSetting ps = mSettings.mPackages.get(packageName);
14328            if (ps == null
14329                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14330                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14331            }
14332            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14333        }
14334    }
14335
14336    @Override
14337    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14338        mContext.enforceCallingOrSelfPermission(
14339                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14340
14341        boolean result = false;
14342        synchronized (mPackages) {
14343            final PackageSetting ps = mSettings.mPackages.get(packageName);
14344            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14345                return false;
14346            }
14347            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14348        }
14349        if (result) {
14350            scheduleWritePackageRestrictionsLocked(userId);
14351        }
14352        return result;
14353    }
14354
14355    @Override
14356    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14357            String packageName) {
14358        final int callingUid = Binder.getCallingUid();
14359        if (getInstantAppPackageName(callingUid) != null) {
14360            return ParceledListSlice.emptyList();
14361        }
14362        synchronized (mPackages) {
14363            final PackageSetting ps = mSettings.mPackages.get(packageName);
14364            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14365                return ParceledListSlice.emptyList();
14366            }
14367            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14368        }
14369    }
14370
14371    @Override
14372    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14373        if (TextUtils.isEmpty(packageName)) {
14374            return ParceledListSlice.emptyList();
14375        }
14376        final int callingUid = Binder.getCallingUid();
14377        final int callingUserId = UserHandle.getUserId(callingUid);
14378        synchronized (mPackages) {
14379            PackageParser.Package pkg = mPackages.get(packageName);
14380            if (pkg == null || pkg.activities == null) {
14381                return ParceledListSlice.emptyList();
14382            }
14383            if (pkg.mExtras == null) {
14384                return ParceledListSlice.emptyList();
14385            }
14386            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14387            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14388                return ParceledListSlice.emptyList();
14389            }
14390            final int count = pkg.activities.size();
14391            ArrayList<IntentFilter> result = new ArrayList<>();
14392            for (int n=0; n<count; n++) {
14393                PackageParser.Activity activity = pkg.activities.get(n);
14394                if (activity.intents != null && activity.intents.size() > 0) {
14395                    result.addAll(activity.intents);
14396                }
14397            }
14398            return new ParceledListSlice<>(result);
14399        }
14400    }
14401
14402    @Override
14403    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14404        mContext.enforceCallingOrSelfPermission(
14405                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14406        if (UserHandle.getCallingUserId() != userId) {
14407            mContext.enforceCallingOrSelfPermission(
14408                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14409        }
14410
14411        synchronized (mPackages) {
14412            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14413            if (packageName != null) {
14414                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14415                        packageName, userId);
14416            }
14417            return result;
14418        }
14419    }
14420
14421    @Override
14422    public String getDefaultBrowserPackageName(int userId) {
14423        if (UserHandle.getCallingUserId() != userId) {
14424            mContext.enforceCallingOrSelfPermission(
14425                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14426        }
14427        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14428            return null;
14429        }
14430        synchronized (mPackages) {
14431            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14432        }
14433    }
14434
14435    /**
14436     * Get the "allow unknown sources" setting.
14437     *
14438     * @return the current "allow unknown sources" setting
14439     */
14440    private int getUnknownSourcesSettings() {
14441        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14442                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14443                -1);
14444    }
14445
14446    @Override
14447    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14448        final int callingUid = Binder.getCallingUid();
14449        if (getInstantAppPackageName(callingUid) != null) {
14450            return;
14451        }
14452        // writer
14453        synchronized (mPackages) {
14454            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14455            if (targetPackageSetting == null
14456                    || filterAppAccessLPr(
14457                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14458                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14459            }
14460
14461            PackageSetting installerPackageSetting;
14462            if (installerPackageName != null) {
14463                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14464                if (installerPackageSetting == null) {
14465                    throw new IllegalArgumentException("Unknown installer package: "
14466                            + installerPackageName);
14467                }
14468            } else {
14469                installerPackageSetting = null;
14470            }
14471
14472            Signature[] callerSignature;
14473            Object obj = mSettings.getUserIdLPr(callingUid);
14474            if (obj != null) {
14475                if (obj instanceof SharedUserSetting) {
14476                    callerSignature =
14477                            ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
14478                } else if (obj instanceof PackageSetting) {
14479                    callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
14480                } else {
14481                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14482                }
14483            } else {
14484                throw new SecurityException("Unknown calling UID: " + callingUid);
14485            }
14486
14487            // Verify: can't set installerPackageName to a package that is
14488            // not signed with the same cert as the caller.
14489            if (installerPackageSetting != null) {
14490                if (compareSignatures(callerSignature,
14491                        installerPackageSetting.signatures.mSigningDetails.signatures)
14492                        != PackageManager.SIGNATURE_MATCH) {
14493                    throw new SecurityException(
14494                            "Caller does not have same cert as new installer package "
14495                            + installerPackageName);
14496                }
14497            }
14498
14499            // Verify: if target already has an installer package, it must
14500            // be signed with the same cert as the caller.
14501            if (targetPackageSetting.installerPackageName != null) {
14502                PackageSetting setting = mSettings.mPackages.get(
14503                        targetPackageSetting.installerPackageName);
14504                // If the currently set package isn't valid, then it's always
14505                // okay to change it.
14506                if (setting != null) {
14507                    if (compareSignatures(callerSignature,
14508                            setting.signatures.mSigningDetails.signatures)
14509                            != PackageManager.SIGNATURE_MATCH) {
14510                        throw new SecurityException(
14511                                "Caller does not have same cert as old installer package "
14512                                + targetPackageSetting.installerPackageName);
14513                    }
14514                }
14515            }
14516
14517            // Okay!
14518            targetPackageSetting.installerPackageName = installerPackageName;
14519            if (installerPackageName != null) {
14520                mSettings.mInstallerPackages.add(installerPackageName);
14521            }
14522            scheduleWriteSettingsLocked();
14523        }
14524    }
14525
14526    @Override
14527    public void setApplicationCategoryHint(String packageName, int categoryHint,
14528            String callerPackageName) {
14529        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14530            throw new SecurityException("Instant applications don't have access to this method");
14531        }
14532        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14533                callerPackageName);
14534        synchronized (mPackages) {
14535            PackageSetting ps = mSettings.mPackages.get(packageName);
14536            if (ps == null) {
14537                throw new IllegalArgumentException("Unknown target package " + packageName);
14538            }
14539            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14540                throw new IllegalArgumentException("Unknown target package " + packageName);
14541            }
14542            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14543                throw new IllegalArgumentException("Calling package " + callerPackageName
14544                        + " is not installer for " + packageName);
14545            }
14546
14547            if (ps.categoryHint != categoryHint) {
14548                ps.categoryHint = categoryHint;
14549                scheduleWriteSettingsLocked();
14550            }
14551        }
14552    }
14553
14554    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14555        // Queue up an async operation since the package installation may take a little while.
14556        mHandler.post(new Runnable() {
14557            public void run() {
14558                mHandler.removeCallbacks(this);
14559                 // Result object to be returned
14560                PackageInstalledInfo res = new PackageInstalledInfo();
14561                res.setReturnCode(currentStatus);
14562                res.uid = -1;
14563                res.pkg = null;
14564                res.removedInfo = null;
14565                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14566                    args.doPreInstall(res.returnCode);
14567                    synchronized (mInstallLock) {
14568                        installPackageTracedLI(args, res);
14569                    }
14570                    args.doPostInstall(res.returnCode, res.uid);
14571                }
14572
14573                // A restore should be performed at this point if (a) the install
14574                // succeeded, (b) the operation is not an update, and (c) the new
14575                // package has not opted out of backup participation.
14576                final boolean update = res.removedInfo != null
14577                        && res.removedInfo.removedPackage != null;
14578                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14579                boolean doRestore = !update
14580                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14581
14582                // Set up the post-install work request bookkeeping.  This will be used
14583                // and cleaned up by the post-install event handling regardless of whether
14584                // there's a restore pass performed.  Token values are >= 1.
14585                int token;
14586                if (mNextInstallToken < 0) mNextInstallToken = 1;
14587                token = mNextInstallToken++;
14588
14589                PostInstallData data = new PostInstallData(args, res);
14590                mRunningInstalls.put(token, data);
14591                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14592
14593                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14594                    // Pass responsibility to the Backup Manager.  It will perform a
14595                    // restore if appropriate, then pass responsibility back to the
14596                    // Package Manager to run the post-install observer callbacks
14597                    // and broadcasts.
14598                    IBackupManager bm = IBackupManager.Stub.asInterface(
14599                            ServiceManager.getService(Context.BACKUP_SERVICE));
14600                    if (bm != null) {
14601                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14602                                + " to BM for possible restore");
14603                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14604                        try {
14605                            // TODO: http://b/22388012
14606                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14607                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14608                            } else {
14609                                doRestore = false;
14610                            }
14611                        } catch (RemoteException e) {
14612                            // can't happen; the backup manager is local
14613                        } catch (Exception e) {
14614                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14615                            doRestore = false;
14616                        }
14617                    } else {
14618                        Slog.e(TAG, "Backup Manager not found!");
14619                        doRestore = false;
14620                    }
14621                }
14622
14623                if (!doRestore) {
14624                    // No restore possible, or the Backup Manager was mysteriously not
14625                    // available -- just fire the post-install work request directly.
14626                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14627
14628                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14629
14630                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14631                    mHandler.sendMessage(msg);
14632                }
14633            }
14634        });
14635    }
14636
14637    /**
14638     * Callback from PackageSettings whenever an app is first transitioned out of the
14639     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14640     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14641     * here whether the app is the target of an ongoing install, and only send the
14642     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14643     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14644     * handling.
14645     */
14646    void notifyFirstLaunch(final String packageName, final String installerPackage,
14647            final int userId) {
14648        // Serialize this with the rest of the install-process message chain.  In the
14649        // restore-at-install case, this Runnable will necessarily run before the
14650        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14651        // are coherent.  In the non-restore case, the app has already completed install
14652        // and been launched through some other means, so it is not in a problematic
14653        // state for observers to see the FIRST_LAUNCH signal.
14654        mHandler.post(new Runnable() {
14655            @Override
14656            public void run() {
14657                for (int i = 0; i < mRunningInstalls.size(); i++) {
14658                    final PostInstallData data = mRunningInstalls.valueAt(i);
14659                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14660                        continue;
14661                    }
14662                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14663                        // right package; but is it for the right user?
14664                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14665                            if (userId == data.res.newUsers[uIndex]) {
14666                                if (DEBUG_BACKUP) {
14667                                    Slog.i(TAG, "Package " + packageName
14668                                            + " being restored so deferring FIRST_LAUNCH");
14669                                }
14670                                return;
14671                            }
14672                        }
14673                    }
14674                }
14675                // didn't find it, so not being restored
14676                if (DEBUG_BACKUP) {
14677                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14678                }
14679                final boolean isInstantApp = isInstantApp(packageName, userId);
14680                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14681                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14682                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14683            }
14684        });
14685    }
14686
14687    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14688            int[] userIds, int[] instantUserIds) {
14689        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14690                installerPkg, null, userIds, instantUserIds);
14691    }
14692
14693    private abstract class HandlerParams {
14694        private static final int MAX_RETRIES = 4;
14695
14696        /**
14697         * Number of times startCopy() has been attempted and had a non-fatal
14698         * error.
14699         */
14700        private int mRetries = 0;
14701
14702        /** User handle for the user requesting the information or installation. */
14703        private final UserHandle mUser;
14704        String traceMethod;
14705        int traceCookie;
14706
14707        HandlerParams(UserHandle user) {
14708            mUser = user;
14709        }
14710
14711        UserHandle getUser() {
14712            return mUser;
14713        }
14714
14715        HandlerParams setTraceMethod(String traceMethod) {
14716            this.traceMethod = traceMethod;
14717            return this;
14718        }
14719
14720        HandlerParams setTraceCookie(int traceCookie) {
14721            this.traceCookie = traceCookie;
14722            return this;
14723        }
14724
14725        final boolean startCopy() {
14726            boolean res;
14727            try {
14728                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14729
14730                if (++mRetries > MAX_RETRIES) {
14731                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14732                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14733                    handleServiceError();
14734                    return false;
14735                } else {
14736                    handleStartCopy();
14737                    res = true;
14738                }
14739            } catch (RemoteException e) {
14740                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14741                mHandler.sendEmptyMessage(MCS_RECONNECT);
14742                res = false;
14743            }
14744            handleReturnCode();
14745            return res;
14746        }
14747
14748        final void serviceError() {
14749            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14750            handleServiceError();
14751            handleReturnCode();
14752        }
14753
14754        abstract void handleStartCopy() throws RemoteException;
14755        abstract void handleServiceError();
14756        abstract void handleReturnCode();
14757    }
14758
14759    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14760        for (File path : paths) {
14761            try {
14762                mcs.clearDirectory(path.getAbsolutePath());
14763            } catch (RemoteException e) {
14764            }
14765        }
14766    }
14767
14768    static class OriginInfo {
14769        /**
14770         * Location where install is coming from, before it has been
14771         * copied/renamed into place. This could be a single monolithic APK
14772         * file, or a cluster directory. This location may be untrusted.
14773         */
14774        final File file;
14775
14776        /**
14777         * Flag indicating that {@link #file} or {@link #cid} has already been
14778         * staged, meaning downstream users don't need to defensively copy the
14779         * contents.
14780         */
14781        final boolean staged;
14782
14783        /**
14784         * Flag indicating that {@link #file} or {@link #cid} is an already
14785         * installed app that is being moved.
14786         */
14787        final boolean existing;
14788
14789        final String resolvedPath;
14790        final File resolvedFile;
14791
14792        static OriginInfo fromNothing() {
14793            return new OriginInfo(null, false, false);
14794        }
14795
14796        static OriginInfo fromUntrustedFile(File file) {
14797            return new OriginInfo(file, false, false);
14798        }
14799
14800        static OriginInfo fromExistingFile(File file) {
14801            return new OriginInfo(file, false, true);
14802        }
14803
14804        static OriginInfo fromStagedFile(File file) {
14805            return new OriginInfo(file, true, false);
14806        }
14807
14808        private OriginInfo(File file, boolean staged, boolean existing) {
14809            this.file = file;
14810            this.staged = staged;
14811            this.existing = existing;
14812
14813            if (file != null) {
14814                resolvedPath = file.getAbsolutePath();
14815                resolvedFile = file;
14816            } else {
14817                resolvedPath = null;
14818                resolvedFile = null;
14819            }
14820        }
14821    }
14822
14823    static class MoveInfo {
14824        final int moveId;
14825        final String fromUuid;
14826        final String toUuid;
14827        final String packageName;
14828        final String dataAppName;
14829        final int appId;
14830        final String seinfo;
14831        final int targetSdkVersion;
14832
14833        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14834                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14835            this.moveId = moveId;
14836            this.fromUuid = fromUuid;
14837            this.toUuid = toUuid;
14838            this.packageName = packageName;
14839            this.dataAppName = dataAppName;
14840            this.appId = appId;
14841            this.seinfo = seinfo;
14842            this.targetSdkVersion = targetSdkVersion;
14843        }
14844    }
14845
14846    static class VerificationInfo {
14847        /** A constant used to indicate that a uid value is not present. */
14848        public static final int NO_UID = -1;
14849
14850        /** URI referencing where the package was downloaded from. */
14851        final Uri originatingUri;
14852
14853        /** HTTP referrer URI associated with the originatingURI. */
14854        final Uri referrer;
14855
14856        /** UID of the application that the install request originated from. */
14857        final int originatingUid;
14858
14859        /** UID of application requesting the install */
14860        final int installerUid;
14861
14862        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14863            this.originatingUri = originatingUri;
14864            this.referrer = referrer;
14865            this.originatingUid = originatingUid;
14866            this.installerUid = installerUid;
14867        }
14868    }
14869
14870    class InstallParams extends HandlerParams {
14871        final OriginInfo origin;
14872        final MoveInfo move;
14873        final IPackageInstallObserver2 observer;
14874        int installFlags;
14875        final String installerPackageName;
14876        final String volumeUuid;
14877        private InstallArgs mArgs;
14878        private int mRet;
14879        final String packageAbiOverride;
14880        final String[] grantedRuntimePermissions;
14881        final VerificationInfo verificationInfo;
14882        final PackageParser.SigningDetails signingDetails;
14883        final int installReason;
14884
14885        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14886                int installFlags, String installerPackageName, String volumeUuid,
14887                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14888                String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
14889            super(user);
14890            this.origin = origin;
14891            this.move = move;
14892            this.observer = observer;
14893            this.installFlags = installFlags;
14894            this.installerPackageName = installerPackageName;
14895            this.volumeUuid = volumeUuid;
14896            this.verificationInfo = verificationInfo;
14897            this.packageAbiOverride = packageAbiOverride;
14898            this.grantedRuntimePermissions = grantedPermissions;
14899            this.signingDetails = signingDetails;
14900            this.installReason = installReason;
14901        }
14902
14903        @Override
14904        public String toString() {
14905            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14906                    + " file=" + origin.file + "}";
14907        }
14908
14909        private int installLocationPolicy(PackageInfoLite pkgLite) {
14910            String packageName = pkgLite.packageName;
14911            int installLocation = pkgLite.installLocation;
14912            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14913            // reader
14914            synchronized (mPackages) {
14915                // Currently installed package which the new package is attempting to replace or
14916                // null if no such package is installed.
14917                PackageParser.Package installedPkg = mPackages.get(packageName);
14918                // Package which currently owns the data which the new package will own if installed.
14919                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14920                // will be null whereas dataOwnerPkg will contain information about the package
14921                // which was uninstalled while keeping its data.
14922                PackageParser.Package dataOwnerPkg = installedPkg;
14923                if (dataOwnerPkg  == null) {
14924                    PackageSetting ps = mSettings.mPackages.get(packageName);
14925                    if (ps != null) {
14926                        dataOwnerPkg = ps.pkg;
14927                    }
14928                }
14929
14930                if (dataOwnerPkg != null) {
14931                    // If installed, the package will get access to data left on the device by its
14932                    // predecessor. As a security measure, this is permited only if this is not a
14933                    // version downgrade or if the predecessor package is marked as debuggable and
14934                    // a downgrade is explicitly requested.
14935                    //
14936                    // On debuggable platform builds, downgrades are permitted even for
14937                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14938                    // not offer security guarantees and thus it's OK to disable some security
14939                    // mechanisms to make debugging/testing easier on those builds. However, even on
14940                    // debuggable builds downgrades of packages are permitted only if requested via
14941                    // installFlags. This is because we aim to keep the behavior of debuggable
14942                    // platform builds as close as possible to the behavior of non-debuggable
14943                    // platform builds.
14944                    final boolean downgradeRequested =
14945                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14946                    final boolean packageDebuggable =
14947                                (dataOwnerPkg.applicationInfo.flags
14948                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14949                    final boolean downgradePermitted =
14950                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14951                    if (!downgradePermitted) {
14952                        try {
14953                            checkDowngrade(dataOwnerPkg, pkgLite);
14954                        } catch (PackageManagerException e) {
14955                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14956                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14957                        }
14958                    }
14959                }
14960
14961                if (installedPkg != null) {
14962                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14963                        // Check for updated system application.
14964                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14965                            if (onSd) {
14966                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14967                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14968                            }
14969                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14970                        } else {
14971                            if (onSd) {
14972                                // Install flag overrides everything.
14973                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14974                            }
14975                            // If current upgrade specifies particular preference
14976                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14977                                // Application explicitly specified internal.
14978                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14979                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14980                                // App explictly prefers external. Let policy decide
14981                            } else {
14982                                // Prefer previous location
14983                                if (isExternal(installedPkg)) {
14984                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14985                                }
14986                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14987                            }
14988                        }
14989                    } else {
14990                        // Invalid install. Return error code
14991                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14992                    }
14993                }
14994            }
14995            // All the special cases have been taken care of.
14996            // Return result based on recommended install location.
14997            if (onSd) {
14998                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14999            }
15000            return pkgLite.recommendedInstallLocation;
15001        }
15002
15003        /*
15004         * Invoke remote method to get package information and install
15005         * location values. Override install location based on default
15006         * policy if needed and then create install arguments based
15007         * on the install location.
15008         */
15009        public void handleStartCopy() throws RemoteException {
15010            int ret = PackageManager.INSTALL_SUCCEEDED;
15011
15012            // If we're already staged, we've firmly committed to an install location
15013            if (origin.staged) {
15014                if (origin.file != null) {
15015                    installFlags |= PackageManager.INSTALL_INTERNAL;
15016                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15017                } else {
15018                    throw new IllegalStateException("Invalid stage location");
15019                }
15020            }
15021
15022            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15023            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15024            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15025            PackageInfoLite pkgLite = null;
15026
15027            if (onInt && onSd) {
15028                // Check if both bits are set.
15029                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15030                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15031            } else if (onSd && ephemeral) {
15032                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15033                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15034            } else {
15035                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15036                        packageAbiOverride);
15037
15038                if (DEBUG_INSTANT && ephemeral) {
15039                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15040                }
15041
15042                /*
15043                 * If we have too little free space, try to free cache
15044                 * before giving up.
15045                 */
15046                if (!origin.staged && pkgLite.recommendedInstallLocation
15047                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15048                    // TODO: focus freeing disk space on the target device
15049                    final StorageManager storage = StorageManager.from(mContext);
15050                    final long lowThreshold = storage.getStorageLowBytes(
15051                            Environment.getDataDirectory());
15052
15053                    final long sizeBytes = mContainerService.calculateInstalledSize(
15054                            origin.resolvedPath, packageAbiOverride);
15055
15056                    try {
15057                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15058                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15059                                installFlags, packageAbiOverride);
15060                    } catch (InstallerException e) {
15061                        Slog.w(TAG, "Failed to free cache", e);
15062                    }
15063
15064                    /*
15065                     * The cache free must have deleted the file we
15066                     * downloaded to install.
15067                     *
15068                     * TODO: fix the "freeCache" call to not delete
15069                     *       the file we care about.
15070                     */
15071                    if (pkgLite.recommendedInstallLocation
15072                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15073                        pkgLite.recommendedInstallLocation
15074                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15075                    }
15076                }
15077            }
15078
15079            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15080                int loc = pkgLite.recommendedInstallLocation;
15081                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15082                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15083                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15084                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15085                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15086                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15087                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15088                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15089                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15090                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15091                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15092                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15093                } else {
15094                    // Override with defaults if needed.
15095                    loc = installLocationPolicy(pkgLite);
15096                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15097                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15098                    } else if (!onSd && !onInt) {
15099                        // Override install location with flags
15100                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15101                            // Set the flag to install on external media.
15102                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15103                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15104                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15105                            if (DEBUG_INSTANT) {
15106                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15107                            }
15108                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15109                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15110                                    |PackageManager.INSTALL_INTERNAL);
15111                        } else {
15112                            // Make sure the flag for installing on external
15113                            // media is unset
15114                            installFlags |= PackageManager.INSTALL_INTERNAL;
15115                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15116                        }
15117                    }
15118                }
15119            }
15120
15121            final InstallArgs args = createInstallArgs(this);
15122            mArgs = args;
15123
15124            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15125                // TODO: http://b/22976637
15126                // Apps installed for "all" users use the device owner to verify the app
15127                UserHandle verifierUser = getUser();
15128                if (verifierUser == UserHandle.ALL) {
15129                    verifierUser = UserHandle.SYSTEM;
15130                }
15131
15132                /*
15133                 * Determine if we have any installed package verifiers. If we
15134                 * do, then we'll defer to them to verify the packages.
15135                 */
15136                final int requiredUid = mRequiredVerifierPackage == null ? -1
15137                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15138                                verifierUser.getIdentifier());
15139                final int installerUid =
15140                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15141                if (!origin.existing && requiredUid != -1
15142                        && isVerificationEnabled(
15143                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15144                    final Intent verification = new Intent(
15145                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15146                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15147                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15148                            PACKAGE_MIME_TYPE);
15149                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15150
15151                    // Query all live verifiers based on current user state
15152                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15153                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15154                            false /*allowDynamicSplits*/);
15155
15156                    if (DEBUG_VERIFY) {
15157                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15158                                + verification.toString() + " with " + pkgLite.verifiers.length
15159                                + " optional verifiers");
15160                    }
15161
15162                    final int verificationId = mPendingVerificationToken++;
15163
15164                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15165
15166                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15167                            installerPackageName);
15168
15169                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15170                            installFlags);
15171
15172                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15173                            pkgLite.packageName);
15174
15175                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15176                            pkgLite.versionCode);
15177
15178                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
15179                            pkgLite.getLongVersionCode());
15180
15181                    if (verificationInfo != null) {
15182                        if (verificationInfo.originatingUri != null) {
15183                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15184                                    verificationInfo.originatingUri);
15185                        }
15186                        if (verificationInfo.referrer != null) {
15187                            verification.putExtra(Intent.EXTRA_REFERRER,
15188                                    verificationInfo.referrer);
15189                        }
15190                        if (verificationInfo.originatingUid >= 0) {
15191                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15192                                    verificationInfo.originatingUid);
15193                        }
15194                        if (verificationInfo.installerUid >= 0) {
15195                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15196                                    verificationInfo.installerUid);
15197                        }
15198                    }
15199
15200                    final PackageVerificationState verificationState = new PackageVerificationState(
15201                            requiredUid, args);
15202
15203                    mPendingVerification.append(verificationId, verificationState);
15204
15205                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15206                            receivers, verificationState);
15207
15208                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15209                    final long idleDuration = getVerificationTimeout();
15210
15211                    /*
15212                     * If any sufficient verifiers were listed in the package
15213                     * manifest, attempt to ask them.
15214                     */
15215                    if (sufficientVerifiers != null) {
15216                        final int N = sufficientVerifiers.size();
15217                        if (N == 0) {
15218                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15219                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15220                        } else {
15221                            for (int i = 0; i < N; i++) {
15222                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15223                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15224                                        verifierComponent.getPackageName(), idleDuration,
15225                                        verifierUser.getIdentifier(), false, "package verifier");
15226
15227                                final Intent sufficientIntent = new Intent(verification);
15228                                sufficientIntent.setComponent(verifierComponent);
15229                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15230                            }
15231                        }
15232                    }
15233
15234                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15235                            mRequiredVerifierPackage, receivers);
15236                    if (ret == PackageManager.INSTALL_SUCCEEDED
15237                            && mRequiredVerifierPackage != null) {
15238                        Trace.asyncTraceBegin(
15239                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15240                        /*
15241                         * Send the intent to the required verification agent,
15242                         * but only start the verification timeout after the
15243                         * target BroadcastReceivers have run.
15244                         */
15245                        verification.setComponent(requiredVerifierComponent);
15246                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15247                                mRequiredVerifierPackage, idleDuration,
15248                                verifierUser.getIdentifier(), false, "package verifier");
15249                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15250                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15251                                new BroadcastReceiver() {
15252                                    @Override
15253                                    public void onReceive(Context context, Intent intent) {
15254                                        final Message msg = mHandler
15255                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15256                                        msg.arg1 = verificationId;
15257                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15258                                    }
15259                                }, null, 0, null, null);
15260
15261                        /*
15262                         * We don't want the copy to proceed until verification
15263                         * succeeds, so null out this field.
15264                         */
15265                        mArgs = null;
15266                    }
15267                } else {
15268                    /*
15269                     * No package verification is enabled, so immediately start
15270                     * the remote call to initiate copy using temporary file.
15271                     */
15272                    ret = args.copyApk(mContainerService, true);
15273                }
15274            }
15275
15276            mRet = ret;
15277        }
15278
15279        @Override
15280        void handleReturnCode() {
15281            // If mArgs is null, then MCS couldn't be reached. When it
15282            // reconnects, it will try again to install. At that point, this
15283            // will succeed.
15284            if (mArgs != null) {
15285                processPendingInstall(mArgs, mRet);
15286            }
15287        }
15288
15289        @Override
15290        void handleServiceError() {
15291            mArgs = createInstallArgs(this);
15292            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15293        }
15294    }
15295
15296    private InstallArgs createInstallArgs(InstallParams params) {
15297        if (params.move != null) {
15298            return new MoveInstallArgs(params);
15299        } else {
15300            return new FileInstallArgs(params);
15301        }
15302    }
15303
15304    /**
15305     * Create args that describe an existing installed package. Typically used
15306     * when cleaning up old installs, or used as a move source.
15307     */
15308    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15309            String resourcePath, String[] instructionSets) {
15310        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15311    }
15312
15313    static abstract class InstallArgs {
15314        /** @see InstallParams#origin */
15315        final OriginInfo origin;
15316        /** @see InstallParams#move */
15317        final MoveInfo move;
15318
15319        final IPackageInstallObserver2 observer;
15320        // Always refers to PackageManager flags only
15321        final int installFlags;
15322        final String installerPackageName;
15323        final String volumeUuid;
15324        final UserHandle user;
15325        final String abiOverride;
15326        final String[] installGrantPermissions;
15327        /** If non-null, drop an async trace when the install completes */
15328        final String traceMethod;
15329        final int traceCookie;
15330        final PackageParser.SigningDetails signingDetails;
15331        final int installReason;
15332
15333        // The list of instruction sets supported by this app. This is currently
15334        // only used during the rmdex() phase to clean up resources. We can get rid of this
15335        // if we move dex files under the common app path.
15336        /* nullable */ String[] instructionSets;
15337
15338        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15339                int installFlags, String installerPackageName, String volumeUuid,
15340                UserHandle user, String[] instructionSets,
15341                String abiOverride, String[] installGrantPermissions,
15342                String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
15343                int installReason) {
15344            this.origin = origin;
15345            this.move = move;
15346            this.installFlags = installFlags;
15347            this.observer = observer;
15348            this.installerPackageName = installerPackageName;
15349            this.volumeUuid = volumeUuid;
15350            this.user = user;
15351            this.instructionSets = instructionSets;
15352            this.abiOverride = abiOverride;
15353            this.installGrantPermissions = installGrantPermissions;
15354            this.traceMethod = traceMethod;
15355            this.traceCookie = traceCookie;
15356            this.signingDetails = signingDetails;
15357            this.installReason = installReason;
15358        }
15359
15360        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15361        abstract int doPreInstall(int status);
15362
15363        /**
15364         * Rename package into final resting place. All paths on the given
15365         * scanned package should be updated to reflect the rename.
15366         */
15367        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15368        abstract int doPostInstall(int status, int uid);
15369
15370        /** @see PackageSettingBase#codePathString */
15371        abstract String getCodePath();
15372        /** @see PackageSettingBase#resourcePathString */
15373        abstract String getResourcePath();
15374
15375        // Need installer lock especially for dex file removal.
15376        abstract void cleanUpResourcesLI();
15377        abstract boolean doPostDeleteLI(boolean delete);
15378
15379        /**
15380         * Called before the source arguments are copied. This is used mostly
15381         * for MoveParams when it needs to read the source file to put it in the
15382         * destination.
15383         */
15384        int doPreCopy() {
15385            return PackageManager.INSTALL_SUCCEEDED;
15386        }
15387
15388        /**
15389         * Called after the source arguments are copied. This is used mostly for
15390         * MoveParams when it needs to read the source file to put it in the
15391         * destination.
15392         */
15393        int doPostCopy(int uid) {
15394            return PackageManager.INSTALL_SUCCEEDED;
15395        }
15396
15397        protected boolean isFwdLocked() {
15398            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15399        }
15400
15401        protected boolean isExternalAsec() {
15402            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15403        }
15404
15405        protected boolean isEphemeral() {
15406            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15407        }
15408
15409        UserHandle getUser() {
15410            return user;
15411        }
15412    }
15413
15414    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15415        if (!allCodePaths.isEmpty()) {
15416            if (instructionSets == null) {
15417                throw new IllegalStateException("instructionSet == null");
15418            }
15419            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15420            for (String codePath : allCodePaths) {
15421                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15422                    try {
15423                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15424                    } catch (InstallerException ignored) {
15425                    }
15426                }
15427            }
15428        }
15429    }
15430
15431    /**
15432     * Logic to handle installation of non-ASEC applications, including copying
15433     * and renaming logic.
15434     */
15435    class FileInstallArgs extends InstallArgs {
15436        private File codeFile;
15437        private File resourceFile;
15438
15439        // Example topology:
15440        // /data/app/com.example/base.apk
15441        // /data/app/com.example/split_foo.apk
15442        // /data/app/com.example/lib/arm/libfoo.so
15443        // /data/app/com.example/lib/arm64/libfoo.so
15444        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15445
15446        /** New install */
15447        FileInstallArgs(InstallParams params) {
15448            super(params.origin, params.move, params.observer, params.installFlags,
15449                    params.installerPackageName, params.volumeUuid,
15450                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15451                    params.grantedRuntimePermissions,
15452                    params.traceMethod, params.traceCookie, params.signingDetails,
15453                    params.installReason);
15454            if (isFwdLocked()) {
15455                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15456            }
15457        }
15458
15459        /** Existing install */
15460        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15461            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15462                    null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15463                    PackageManager.INSTALL_REASON_UNKNOWN);
15464            this.codeFile = (codePath != null) ? new File(codePath) : null;
15465            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15466        }
15467
15468        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15469            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15470            try {
15471                return doCopyApk(imcs, temp);
15472            } finally {
15473                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15474            }
15475        }
15476
15477        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15478            if (origin.staged) {
15479                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15480                codeFile = origin.file;
15481                resourceFile = origin.file;
15482                return PackageManager.INSTALL_SUCCEEDED;
15483            }
15484
15485            try {
15486                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15487                final File tempDir =
15488                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15489                codeFile = tempDir;
15490                resourceFile = tempDir;
15491            } catch (IOException e) {
15492                Slog.w(TAG, "Failed to create copy file: " + e);
15493                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15494            }
15495
15496            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15497                @Override
15498                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15499                    if (!FileUtils.isValidExtFilename(name)) {
15500                        throw new IllegalArgumentException("Invalid filename: " + name);
15501                    }
15502                    try {
15503                        final File file = new File(codeFile, name);
15504                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15505                                O_RDWR | O_CREAT, 0644);
15506                        Os.chmod(file.getAbsolutePath(), 0644);
15507                        return new ParcelFileDescriptor(fd);
15508                    } catch (ErrnoException e) {
15509                        throw new RemoteException("Failed to open: " + e.getMessage());
15510                    }
15511                }
15512            };
15513
15514            int ret = PackageManager.INSTALL_SUCCEEDED;
15515            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15516            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15517                Slog.e(TAG, "Failed to copy package");
15518                return ret;
15519            }
15520
15521            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15522            NativeLibraryHelper.Handle handle = null;
15523            try {
15524                handle = NativeLibraryHelper.Handle.create(codeFile);
15525                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15526                        abiOverride);
15527            } catch (IOException e) {
15528                Slog.e(TAG, "Copying native libraries failed", e);
15529                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15530            } finally {
15531                IoUtils.closeQuietly(handle);
15532            }
15533
15534            return ret;
15535        }
15536
15537        int doPreInstall(int status) {
15538            if (status != PackageManager.INSTALL_SUCCEEDED) {
15539                cleanUp();
15540            }
15541            return status;
15542        }
15543
15544        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15545            if (status != PackageManager.INSTALL_SUCCEEDED) {
15546                cleanUp();
15547                return false;
15548            }
15549
15550            final File targetDir = codeFile.getParentFile();
15551            final File beforeCodeFile = codeFile;
15552            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15553
15554            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15555            try {
15556                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15557            } catch (ErrnoException e) {
15558                Slog.w(TAG, "Failed to rename", e);
15559                return false;
15560            }
15561
15562            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15563                Slog.w(TAG, "Failed to restorecon");
15564                return false;
15565            }
15566
15567            // Reflect the rename internally
15568            codeFile = afterCodeFile;
15569            resourceFile = afterCodeFile;
15570
15571            // Reflect the rename in scanned details
15572            try {
15573                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15574            } catch (IOException e) {
15575                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15576                return false;
15577            }
15578            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15579                    afterCodeFile, pkg.baseCodePath));
15580            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15581                    afterCodeFile, pkg.splitCodePaths));
15582
15583            // Reflect the rename in app info
15584            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15585            pkg.setApplicationInfoCodePath(pkg.codePath);
15586            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15587            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15588            pkg.setApplicationInfoResourcePath(pkg.codePath);
15589            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15590            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15591
15592            return true;
15593        }
15594
15595        int doPostInstall(int status, int uid) {
15596            if (status != PackageManager.INSTALL_SUCCEEDED) {
15597                cleanUp();
15598            }
15599            return status;
15600        }
15601
15602        @Override
15603        String getCodePath() {
15604            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15605        }
15606
15607        @Override
15608        String getResourcePath() {
15609            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15610        }
15611
15612        private boolean cleanUp() {
15613            if (codeFile == null || !codeFile.exists()) {
15614                return false;
15615            }
15616
15617            removeCodePathLI(codeFile);
15618
15619            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15620                resourceFile.delete();
15621            }
15622
15623            return true;
15624        }
15625
15626        void cleanUpResourcesLI() {
15627            // Try enumerating all code paths before deleting
15628            List<String> allCodePaths = Collections.EMPTY_LIST;
15629            if (codeFile != null && codeFile.exists()) {
15630                try {
15631                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15632                    allCodePaths = pkg.getAllCodePaths();
15633                } catch (PackageParserException e) {
15634                    // Ignored; we tried our best
15635                }
15636            }
15637
15638            cleanUp();
15639            removeDexFiles(allCodePaths, instructionSets);
15640        }
15641
15642        boolean doPostDeleteLI(boolean delete) {
15643            // XXX err, shouldn't we respect the delete flag?
15644            cleanUpResourcesLI();
15645            return true;
15646        }
15647    }
15648
15649    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15650            PackageManagerException {
15651        if (copyRet < 0) {
15652            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15653                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15654                throw new PackageManagerException(copyRet, message);
15655            }
15656        }
15657    }
15658
15659    /**
15660     * Extract the StorageManagerService "container ID" from the full code path of an
15661     * .apk.
15662     */
15663    static String cidFromCodePath(String fullCodePath) {
15664        int eidx = fullCodePath.lastIndexOf("/");
15665        String subStr1 = fullCodePath.substring(0, eidx);
15666        int sidx = subStr1.lastIndexOf("/");
15667        return subStr1.substring(sidx+1, eidx);
15668    }
15669
15670    /**
15671     * Logic to handle movement of existing installed applications.
15672     */
15673    class MoveInstallArgs extends InstallArgs {
15674        private File codeFile;
15675        private File resourceFile;
15676
15677        /** New install */
15678        MoveInstallArgs(InstallParams params) {
15679            super(params.origin, params.move, params.observer, params.installFlags,
15680                    params.installerPackageName, params.volumeUuid,
15681                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15682                    params.grantedRuntimePermissions,
15683                    params.traceMethod, params.traceCookie, params.signingDetails,
15684                    params.installReason);
15685        }
15686
15687        int copyApk(IMediaContainerService imcs, boolean temp) {
15688            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15689                    + move.fromUuid + " to " + move.toUuid);
15690            synchronized (mInstaller) {
15691                try {
15692                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15693                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15694                } catch (InstallerException e) {
15695                    Slog.w(TAG, "Failed to move app", e);
15696                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15697                }
15698            }
15699
15700            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15701            resourceFile = codeFile;
15702            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15703
15704            return PackageManager.INSTALL_SUCCEEDED;
15705        }
15706
15707        int doPreInstall(int status) {
15708            if (status != PackageManager.INSTALL_SUCCEEDED) {
15709                cleanUp(move.toUuid);
15710            }
15711            return status;
15712        }
15713
15714        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15715            if (status != PackageManager.INSTALL_SUCCEEDED) {
15716                cleanUp(move.toUuid);
15717                return false;
15718            }
15719
15720            // Reflect the move in app info
15721            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15722            pkg.setApplicationInfoCodePath(pkg.codePath);
15723            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15724            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15725            pkg.setApplicationInfoResourcePath(pkg.codePath);
15726            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15727            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15728
15729            return true;
15730        }
15731
15732        int doPostInstall(int status, int uid) {
15733            if (status == PackageManager.INSTALL_SUCCEEDED) {
15734                cleanUp(move.fromUuid);
15735            } else {
15736                cleanUp(move.toUuid);
15737            }
15738            return status;
15739        }
15740
15741        @Override
15742        String getCodePath() {
15743            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15744        }
15745
15746        @Override
15747        String getResourcePath() {
15748            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15749        }
15750
15751        private boolean cleanUp(String volumeUuid) {
15752            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15753                    move.dataAppName);
15754            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15755            final int[] userIds = sUserManager.getUserIds();
15756            synchronized (mInstallLock) {
15757                // Clean up both app data and code
15758                // All package moves are frozen until finished
15759                for (int userId : userIds) {
15760                    try {
15761                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15762                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15763                    } catch (InstallerException e) {
15764                        Slog.w(TAG, String.valueOf(e));
15765                    }
15766                }
15767                removeCodePathLI(codeFile);
15768            }
15769            return true;
15770        }
15771
15772        void cleanUpResourcesLI() {
15773            throw new UnsupportedOperationException();
15774        }
15775
15776        boolean doPostDeleteLI(boolean delete) {
15777            throw new UnsupportedOperationException();
15778        }
15779    }
15780
15781    static String getAsecPackageName(String packageCid) {
15782        int idx = packageCid.lastIndexOf("-");
15783        if (idx == -1) {
15784            return packageCid;
15785        }
15786        return packageCid.substring(0, idx);
15787    }
15788
15789    // Utility method used to create code paths based on package name and available index.
15790    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15791        String idxStr = "";
15792        int idx = 1;
15793        // Fall back to default value of idx=1 if prefix is not
15794        // part of oldCodePath
15795        if (oldCodePath != null) {
15796            String subStr = oldCodePath;
15797            // Drop the suffix right away
15798            if (suffix != null && subStr.endsWith(suffix)) {
15799                subStr = subStr.substring(0, subStr.length() - suffix.length());
15800            }
15801            // If oldCodePath already contains prefix find out the
15802            // ending index to either increment or decrement.
15803            int sidx = subStr.lastIndexOf(prefix);
15804            if (sidx != -1) {
15805                subStr = subStr.substring(sidx + prefix.length());
15806                if (subStr != null) {
15807                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15808                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15809                    }
15810                    try {
15811                        idx = Integer.parseInt(subStr);
15812                        if (idx <= 1) {
15813                            idx++;
15814                        } else {
15815                            idx--;
15816                        }
15817                    } catch(NumberFormatException e) {
15818                    }
15819                }
15820            }
15821        }
15822        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15823        return prefix + idxStr;
15824    }
15825
15826    private File getNextCodePath(File targetDir, String packageName) {
15827        File result;
15828        SecureRandom random = new SecureRandom();
15829        byte[] bytes = new byte[16];
15830        do {
15831            random.nextBytes(bytes);
15832            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15833            result = new File(targetDir, packageName + "-" + suffix);
15834        } while (result.exists());
15835        return result;
15836    }
15837
15838    // Utility method that returns the relative package path with respect
15839    // to the installation directory. Like say for /data/data/com.test-1.apk
15840    // string com.test-1 is returned.
15841    static String deriveCodePathName(String codePath) {
15842        if (codePath == null) {
15843            return null;
15844        }
15845        final File codeFile = new File(codePath);
15846        final String name = codeFile.getName();
15847        if (codeFile.isDirectory()) {
15848            return name;
15849        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15850            final int lastDot = name.lastIndexOf('.');
15851            return name.substring(0, lastDot);
15852        } else {
15853            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15854            return null;
15855        }
15856    }
15857
15858    static class PackageInstalledInfo {
15859        String name;
15860        int uid;
15861        // The set of users that originally had this package installed.
15862        int[] origUsers;
15863        // The set of users that now have this package installed.
15864        int[] newUsers;
15865        PackageParser.Package pkg;
15866        int returnCode;
15867        String returnMsg;
15868        String installerPackageName;
15869        PackageRemovedInfo removedInfo;
15870        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15871
15872        public void setError(int code, String msg) {
15873            setReturnCode(code);
15874            setReturnMessage(msg);
15875            Slog.w(TAG, msg);
15876        }
15877
15878        public void setError(String msg, PackageParserException e) {
15879            setReturnCode(e.error);
15880            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15881            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15882            for (int i = 0; i < childCount; i++) {
15883                addedChildPackages.valueAt(i).setError(msg, e);
15884            }
15885            Slog.w(TAG, msg, e);
15886        }
15887
15888        public void setError(String msg, PackageManagerException e) {
15889            returnCode = e.error;
15890            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15891            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15892            for (int i = 0; i < childCount; i++) {
15893                addedChildPackages.valueAt(i).setError(msg, e);
15894            }
15895            Slog.w(TAG, msg, e);
15896        }
15897
15898        public void setReturnCode(int returnCode) {
15899            this.returnCode = returnCode;
15900            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15901            for (int i = 0; i < childCount; i++) {
15902                addedChildPackages.valueAt(i).returnCode = returnCode;
15903            }
15904        }
15905
15906        private void setReturnMessage(String returnMsg) {
15907            this.returnMsg = returnMsg;
15908            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15909            for (int i = 0; i < childCount; i++) {
15910                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15911            }
15912        }
15913
15914        // In some error cases we want to convey more info back to the observer
15915        String origPackage;
15916        String origPermission;
15917    }
15918
15919    /*
15920     * Install a non-existing package.
15921     */
15922    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15923            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15924            String volumeUuid, PackageInstalledInfo res, int installReason) {
15925        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15926
15927        // Remember this for later, in case we need to rollback this install
15928        String pkgName = pkg.packageName;
15929
15930        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15931
15932        synchronized(mPackages) {
15933            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15934            if (renamedPackage != null) {
15935                // A package with the same name is already installed, though
15936                // it has been renamed to an older name.  The package we
15937                // are trying to install should be installed as an update to
15938                // the existing one, but that has not been requested, so bail.
15939                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15940                        + " without first uninstalling package running as "
15941                        + renamedPackage);
15942                return;
15943            }
15944            if (mPackages.containsKey(pkgName)) {
15945                // Don't allow installation over an existing package with the same name.
15946                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15947                        + " without first uninstalling.");
15948                return;
15949            }
15950        }
15951
15952        try {
15953            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
15954                    System.currentTimeMillis(), user);
15955
15956            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15957
15958            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15959                prepareAppDataAfterInstallLIF(newPackage);
15960
15961            } else {
15962                // Remove package from internal structures, but keep around any
15963                // data that might have already existed
15964                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15965                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15966            }
15967        } catch (PackageManagerException e) {
15968            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15969        }
15970
15971        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15972    }
15973
15974    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15975        try (DigestInputStream digestStream =
15976                new DigestInputStream(new FileInputStream(file), digest)) {
15977            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15978        }
15979    }
15980
15981    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15982            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15983            PackageInstalledInfo res, int installReason) {
15984        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15985
15986        final PackageParser.Package oldPackage;
15987        final PackageSetting ps;
15988        final String pkgName = pkg.packageName;
15989        final int[] allUsers;
15990        final int[] installedUsers;
15991
15992        synchronized(mPackages) {
15993            oldPackage = mPackages.get(pkgName);
15994            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15995
15996            // don't allow upgrade to target a release SDK from a pre-release SDK
15997            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15998                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15999            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16000                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16001            if (oldTargetsPreRelease
16002                    && !newTargetsPreRelease
16003                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16004                Slog.w(TAG, "Can't install package targeting released sdk");
16005                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16006                return;
16007            }
16008
16009            ps = mSettings.mPackages.get(pkgName);
16010
16011            // verify signatures are valid
16012            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16013            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
16014                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
16015                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16016                            "New package not signed by keys specified by upgrade-keysets: "
16017                                    + pkgName);
16018                    return;
16019                }
16020            } else {
16021
16022                // default to original signature matching
16023                if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails,
16024                        PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
16025                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16026                            "New package has a different signature: " + pkgName);
16027                    return;
16028                }
16029            }
16030
16031            // don't allow a system upgrade unless the upgrade hash matches
16032            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
16033                byte[] digestBytes = null;
16034                try {
16035                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16036                    updateDigest(digest, new File(pkg.baseCodePath));
16037                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16038                        for (String path : pkg.splitCodePaths) {
16039                            updateDigest(digest, new File(path));
16040                        }
16041                    }
16042                    digestBytes = digest.digest();
16043                } catch (NoSuchAlgorithmException | IOException e) {
16044                    res.setError(INSTALL_FAILED_INVALID_APK,
16045                            "Could not compute hash: " + pkgName);
16046                    return;
16047                }
16048                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16049                    res.setError(INSTALL_FAILED_INVALID_APK,
16050                            "New package fails restrict-update check: " + pkgName);
16051                    return;
16052                }
16053                // retain upgrade restriction
16054                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16055            }
16056
16057            // Check for shared user id changes
16058            String invalidPackageName =
16059                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16060            if (invalidPackageName != null) {
16061                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16062                        "Package " + invalidPackageName + " tried to change user "
16063                                + oldPackage.mSharedUserId);
16064                return;
16065            }
16066
16067            // check if the new package supports all of the abis which the old package supports
16068            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
16069            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
16070            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
16071                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16072                        "Update to package " + pkgName + " doesn't support multi arch");
16073                return;
16074            }
16075
16076            // In case of rollback, remember per-user/profile install state
16077            allUsers = sUserManager.getUserIds();
16078            installedUsers = ps.queryInstalledUsers(allUsers, true);
16079
16080            // don't allow an upgrade from full to ephemeral
16081            if (isInstantApp) {
16082                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16083                    for (int currentUser : allUsers) {
16084                        if (!ps.getInstantApp(currentUser)) {
16085                            // can't downgrade from full to instant
16086                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16087                                    + " for user: " + currentUser);
16088                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16089                            return;
16090                        }
16091                    }
16092                } else if (!ps.getInstantApp(user.getIdentifier())) {
16093                    // can't downgrade from full to instant
16094                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16095                            + " for user: " + user.getIdentifier());
16096                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16097                    return;
16098                }
16099            }
16100        }
16101
16102        // Update what is removed
16103        res.removedInfo = new PackageRemovedInfo(this);
16104        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16105        res.removedInfo.removedPackage = oldPackage.packageName;
16106        res.removedInfo.installerPackageName = ps.installerPackageName;
16107        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16108        res.removedInfo.isUpdate = true;
16109        res.removedInfo.origUsers = installedUsers;
16110        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16111        for (int i = 0; i < installedUsers.length; i++) {
16112            final int userId = installedUsers[i];
16113            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16114        }
16115
16116        final int childCount = (oldPackage.childPackages != null)
16117                ? oldPackage.childPackages.size() : 0;
16118        for (int i = 0; i < childCount; i++) {
16119            boolean childPackageUpdated = false;
16120            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16121            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16122            if (res.addedChildPackages != null) {
16123                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16124                if (childRes != null) {
16125                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16126                    childRes.removedInfo.removedPackage = childPkg.packageName;
16127                    if (childPs != null) {
16128                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16129                    }
16130                    childRes.removedInfo.isUpdate = true;
16131                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16132                    childPackageUpdated = true;
16133                }
16134            }
16135            if (!childPackageUpdated) {
16136                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16137                childRemovedRes.removedPackage = childPkg.packageName;
16138                if (childPs != null) {
16139                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16140                }
16141                childRemovedRes.isUpdate = false;
16142                childRemovedRes.dataRemoved = true;
16143                synchronized (mPackages) {
16144                    if (childPs != null) {
16145                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16146                    }
16147                }
16148                if (res.removedInfo.removedChildPackages == null) {
16149                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16150                }
16151                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16152            }
16153        }
16154
16155        boolean sysPkg = (isSystemApp(oldPackage));
16156        if (sysPkg) {
16157            // Set the system/privileged/oem/vendor/product flags as needed
16158            final boolean privileged =
16159                    (oldPackage.applicationInfo.privateFlags
16160                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16161            final boolean oem =
16162                    (oldPackage.applicationInfo.privateFlags
16163                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16164            final boolean vendor =
16165                    (oldPackage.applicationInfo.privateFlags
16166                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
16167            final boolean product =
16168                    (oldPackage.applicationInfo.privateFlags
16169                            & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
16170            final @ParseFlags int systemParseFlags = parseFlags;
16171            final @ScanFlags int systemScanFlags = scanFlags
16172                    | SCAN_AS_SYSTEM
16173                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
16174                    | (oem ? SCAN_AS_OEM : 0)
16175                    | (vendor ? SCAN_AS_VENDOR : 0)
16176                    | (product ? SCAN_AS_PRODUCT : 0);
16177
16178            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
16179                    user, allUsers, installerPackageName, res, installReason);
16180        } else {
16181            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
16182                    user, allUsers, installerPackageName, res, installReason);
16183        }
16184    }
16185
16186    @Override
16187    public List<String> getPreviousCodePaths(String packageName) {
16188        final int callingUid = Binder.getCallingUid();
16189        final List<String> result = new ArrayList<>();
16190        if (getInstantAppPackageName(callingUid) != null) {
16191            return result;
16192        }
16193        final PackageSetting ps = mSettings.mPackages.get(packageName);
16194        if (ps != null
16195                && ps.oldCodePaths != null
16196                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
16197            result.addAll(ps.oldCodePaths);
16198        }
16199        return result;
16200    }
16201
16202    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16203            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16204            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
16205            String installerPackageName, PackageInstalledInfo res, int installReason) {
16206        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16207                + deletedPackage);
16208
16209        String pkgName = deletedPackage.packageName;
16210        boolean deletedPkg = true;
16211        boolean addedPkg = false;
16212        boolean updatedSettings = false;
16213        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16214        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16215                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16216
16217        final long origUpdateTime = (pkg.mExtras != null)
16218                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16219
16220        // First delete the existing package while retaining the data directory
16221        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16222                res.removedInfo, true, pkg)) {
16223            // If the existing package wasn't successfully deleted
16224            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16225            deletedPkg = false;
16226        } else {
16227            // Successfully deleted the old package; proceed with replace.
16228
16229            // If deleted package lived in a container, give users a chance to
16230            // relinquish resources before killing.
16231            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16232                if (DEBUG_INSTALL) {
16233                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16234                }
16235                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16236                final ArrayList<String> pkgList = new ArrayList<String>(1);
16237                pkgList.add(deletedPackage.applicationInfo.packageName);
16238                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16239            }
16240
16241            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16242                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16243
16244            try {
16245                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
16246                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16247                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16248                        installReason);
16249
16250                // Update the in-memory copy of the previous code paths.
16251                PackageSetting ps = mSettings.mPackages.get(pkgName);
16252                if (!killApp) {
16253                    if (ps.oldCodePaths == null) {
16254                        ps.oldCodePaths = new ArraySet<>();
16255                    }
16256                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16257                    if (deletedPackage.splitCodePaths != null) {
16258                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16259                    }
16260                } else {
16261                    ps.oldCodePaths = null;
16262                }
16263                if (ps.childPackageNames != null) {
16264                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16265                        final String childPkgName = ps.childPackageNames.get(i);
16266                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16267                        childPs.oldCodePaths = ps.oldCodePaths;
16268                    }
16269                }
16270                // set instant app status, but, only if it's explicitly specified
16271                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16272                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16273                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16274                prepareAppDataAfterInstallLIF(newPackage);
16275                addedPkg = true;
16276                mDexManager.notifyPackageUpdated(newPackage.packageName,
16277                        newPackage.baseCodePath, newPackage.splitCodePaths);
16278            } catch (PackageManagerException e) {
16279                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16280            }
16281        }
16282
16283        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16284            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16285
16286            // Revert all internal state mutations and added folders for the failed install
16287            if (addedPkg) {
16288                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16289                        res.removedInfo, true, null);
16290            }
16291
16292            // Restore the old package
16293            if (deletedPkg) {
16294                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16295                File restoreFile = new File(deletedPackage.codePath);
16296                // Parse old package
16297                boolean oldExternal = isExternal(deletedPackage);
16298                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16299                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16300                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16301                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16302                try {
16303                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16304                            null);
16305                } catch (PackageManagerException e) {
16306                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16307                            + e.getMessage());
16308                    return;
16309                }
16310
16311                synchronized (mPackages) {
16312                    // Ensure the installer package name up to date
16313                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16314
16315                    // Update permissions for restored package
16316                    mPermissionManager.updatePermissions(
16317                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16318                            mPermissionCallback);
16319
16320                    mSettings.writeLPr();
16321                }
16322
16323                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16324            }
16325        } else {
16326            synchronized (mPackages) {
16327                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16328                if (ps != null) {
16329                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16330                    if (res.removedInfo.removedChildPackages != null) {
16331                        final int childCount = res.removedInfo.removedChildPackages.size();
16332                        // Iterate in reverse as we may modify the collection
16333                        for (int i = childCount - 1; i >= 0; i--) {
16334                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16335                            if (res.addedChildPackages.containsKey(childPackageName)) {
16336                                res.removedInfo.removedChildPackages.removeAt(i);
16337                            } else {
16338                                PackageRemovedInfo childInfo = res.removedInfo
16339                                        .removedChildPackages.valueAt(i);
16340                                childInfo.removedForAllUsers = mPackages.get(
16341                                        childInfo.removedPackage) == null;
16342                            }
16343                        }
16344                    }
16345                }
16346            }
16347        }
16348    }
16349
16350    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16351            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16352            final @ScanFlags int scanFlags, UserHandle user,
16353            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16354            int installReason) {
16355        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16356                + ", old=" + deletedPackage);
16357
16358        final boolean disabledSystem;
16359
16360        // Remove existing system package
16361        removePackageLI(deletedPackage, true);
16362
16363        synchronized (mPackages) {
16364            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16365        }
16366        if (!disabledSystem) {
16367            // We didn't need to disable the .apk as a current system package,
16368            // which means we are replacing another update that is already
16369            // installed.  We need to make sure to delete the older one's .apk.
16370            res.removedInfo.args = createInstallArgsForExisting(0,
16371                    deletedPackage.applicationInfo.getCodePath(),
16372                    deletedPackage.applicationInfo.getResourcePath(),
16373                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16374        } else {
16375            res.removedInfo.args = null;
16376        }
16377
16378        // Successfully disabled the old package. Now proceed with re-installation
16379        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16380                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16381
16382        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16383        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16384                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16385
16386        PackageParser.Package newPackage = null;
16387        try {
16388            // Add the package to the internal data structures
16389            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16390
16391            // Set the update and install times
16392            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16393            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16394                    System.currentTimeMillis());
16395
16396            // Update the package dynamic state if succeeded
16397            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16398                // Now that the install succeeded make sure we remove data
16399                // directories for any child package the update removed.
16400                final int deletedChildCount = (deletedPackage.childPackages != null)
16401                        ? deletedPackage.childPackages.size() : 0;
16402                final int newChildCount = (newPackage.childPackages != null)
16403                        ? newPackage.childPackages.size() : 0;
16404                for (int i = 0; i < deletedChildCount; i++) {
16405                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16406                    boolean childPackageDeleted = true;
16407                    for (int j = 0; j < newChildCount; j++) {
16408                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16409                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16410                            childPackageDeleted = false;
16411                            break;
16412                        }
16413                    }
16414                    if (childPackageDeleted) {
16415                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16416                                deletedChildPkg.packageName);
16417                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16418                            PackageRemovedInfo removedChildRes = res.removedInfo
16419                                    .removedChildPackages.get(deletedChildPkg.packageName);
16420                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16421                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16422                        }
16423                    }
16424                }
16425
16426                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16427                        installReason);
16428                prepareAppDataAfterInstallLIF(newPackage);
16429
16430                mDexManager.notifyPackageUpdated(newPackage.packageName,
16431                            newPackage.baseCodePath, newPackage.splitCodePaths);
16432            }
16433        } catch (PackageManagerException e) {
16434            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16435            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16436        }
16437
16438        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16439            // Re installation failed. Restore old information
16440            // Remove new pkg information
16441            if (newPackage != null) {
16442                removeInstalledPackageLI(newPackage, true);
16443            }
16444            // Add back the old system package
16445            try {
16446                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16447            } catch (PackageManagerException e) {
16448                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16449            }
16450
16451            synchronized (mPackages) {
16452                if (disabledSystem) {
16453                    enableSystemPackageLPw(deletedPackage);
16454                }
16455
16456                // Ensure the installer package name up to date
16457                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16458
16459                // Update permissions for restored package
16460                mPermissionManager.updatePermissions(
16461                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16462                        mPermissionCallback);
16463
16464                mSettings.writeLPr();
16465            }
16466
16467            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16468                    + " after failed upgrade");
16469        }
16470    }
16471
16472    /**
16473     * Checks whether the parent or any of the child packages have a change shared
16474     * user. For a package to be a valid update the shred users of the parent and
16475     * the children should match. We may later support changing child shared users.
16476     * @param oldPkg The updated package.
16477     * @param newPkg The update package.
16478     * @return The shared user that change between the versions.
16479     */
16480    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16481            PackageParser.Package newPkg) {
16482        // Check parent shared user
16483        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16484            return newPkg.packageName;
16485        }
16486        // Check child shared users
16487        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16488        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16489        for (int i = 0; i < newChildCount; i++) {
16490            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16491            // If this child was present, did it have the same shared user?
16492            for (int j = 0; j < oldChildCount; j++) {
16493                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16494                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16495                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16496                    return newChildPkg.packageName;
16497                }
16498            }
16499        }
16500        return null;
16501    }
16502
16503    private void removeNativeBinariesLI(PackageSetting ps) {
16504        // Remove the lib path for the parent package
16505        if (ps != null) {
16506            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16507            // Remove the lib path for the child packages
16508            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16509            for (int i = 0; i < childCount; i++) {
16510                PackageSetting childPs = null;
16511                synchronized (mPackages) {
16512                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16513                }
16514                if (childPs != null) {
16515                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16516                            .legacyNativeLibraryPathString);
16517                }
16518            }
16519        }
16520    }
16521
16522    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16523        // Enable the parent package
16524        mSettings.enableSystemPackageLPw(pkg.packageName);
16525        // Enable the child packages
16526        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16527        for (int i = 0; i < childCount; i++) {
16528            PackageParser.Package childPkg = pkg.childPackages.get(i);
16529            mSettings.enableSystemPackageLPw(childPkg.packageName);
16530        }
16531    }
16532
16533    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16534            PackageParser.Package newPkg) {
16535        // Disable the parent package (parent always replaced)
16536        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16537        // Disable the child packages
16538        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16539        for (int i = 0; i < childCount; i++) {
16540            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16541            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16542            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16543        }
16544        return disabled;
16545    }
16546
16547    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16548            String installerPackageName) {
16549        // Enable the parent package
16550        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16551        // Enable the child packages
16552        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16553        for (int i = 0; i < childCount; i++) {
16554            PackageParser.Package childPkg = pkg.childPackages.get(i);
16555            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16556        }
16557    }
16558
16559    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16560            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16561        // Update the parent package setting
16562        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16563                res, user, installReason);
16564        // Update the child packages setting
16565        final int childCount = (newPackage.childPackages != null)
16566                ? newPackage.childPackages.size() : 0;
16567        for (int i = 0; i < childCount; i++) {
16568            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16569            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16570            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16571                    childRes.origUsers, childRes, user, installReason);
16572        }
16573    }
16574
16575    private void updateSettingsInternalLI(PackageParser.Package pkg,
16576            String installerPackageName, int[] allUsers, int[] installedForUsers,
16577            PackageInstalledInfo res, UserHandle user, int installReason) {
16578        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16579
16580        final String pkgName = pkg.packageName;
16581
16582        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16583        synchronized (mPackages) {
16584// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16585            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16586                    mPermissionCallback);
16587            // For system-bundled packages, we assume that installing an upgraded version
16588            // of the package implies that the user actually wants to run that new code,
16589            // so we enable the package.
16590            PackageSetting ps = mSettings.mPackages.get(pkgName);
16591            final int userId = user.getIdentifier();
16592            if (ps != null) {
16593                if (isSystemApp(pkg)) {
16594                    if (DEBUG_INSTALL) {
16595                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16596                    }
16597                    // Enable system package for requested users
16598                    if (res.origUsers != null) {
16599                        for (int origUserId : res.origUsers) {
16600                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16601                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16602                                        origUserId, installerPackageName);
16603                            }
16604                        }
16605                    }
16606                    // Also convey the prior install/uninstall state
16607                    if (allUsers != null && installedForUsers != null) {
16608                        for (int currentUserId : allUsers) {
16609                            final boolean installed = ArrayUtils.contains(
16610                                    installedForUsers, currentUserId);
16611                            if (DEBUG_INSTALL) {
16612                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16613                            }
16614                            ps.setInstalled(installed, currentUserId);
16615                        }
16616                        // these install state changes will be persisted in the
16617                        // upcoming call to mSettings.writeLPr().
16618                    }
16619                }
16620                // It's implied that when a user requests installation, they want the app to be
16621                // installed and enabled.
16622                if (userId != UserHandle.USER_ALL) {
16623                    ps.setInstalled(true, userId);
16624                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16625                } else {
16626                    for (int currentUserId : sUserManager.getUserIds()) {
16627                        ps.setInstalled(true, currentUserId);
16628                        ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, currentUserId,
16629                                installerPackageName);
16630                    }
16631                }
16632
16633                // When replacing an existing package, preserve the original install reason for all
16634                // users that had the package installed before.
16635                final Set<Integer> previousUserIds = new ArraySet<>();
16636                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16637                    final int installReasonCount = res.removedInfo.installReasons.size();
16638                    for (int i = 0; i < installReasonCount; i++) {
16639                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16640                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16641                        ps.setInstallReason(previousInstallReason, previousUserId);
16642                        previousUserIds.add(previousUserId);
16643                    }
16644                }
16645
16646                // Set install reason for users that are having the package newly installed.
16647                if (userId == UserHandle.USER_ALL) {
16648                    for (int currentUserId : sUserManager.getUserIds()) {
16649                        if (!previousUserIds.contains(currentUserId)) {
16650                            ps.setInstallReason(installReason, currentUserId);
16651                        }
16652                    }
16653                } else if (!previousUserIds.contains(userId)) {
16654                    ps.setInstallReason(installReason, userId);
16655                }
16656                mSettings.writeKernelMappingLPr(ps);
16657            }
16658            res.name = pkgName;
16659            res.uid = pkg.applicationInfo.uid;
16660            res.pkg = pkg;
16661            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16662            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16663            //to update install status
16664            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16665            mSettings.writeLPr();
16666            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16667        }
16668
16669        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16670    }
16671
16672    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16673        try {
16674            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16675            installPackageLI(args, res);
16676        } finally {
16677            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16678        }
16679    }
16680
16681    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16682        final int installFlags = args.installFlags;
16683        final String installerPackageName = args.installerPackageName;
16684        final String volumeUuid = args.volumeUuid;
16685        final File tmpPackageFile = new File(args.getCodePath());
16686        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16687        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16688                || (args.volumeUuid != null));
16689        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16690        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16691        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16692        final boolean virtualPreload =
16693                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16694        boolean replace = false;
16695        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16696        if (args.move != null) {
16697            // moving a complete application; perform an initial scan on the new install location
16698            scanFlags |= SCAN_INITIAL;
16699        }
16700        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16701            scanFlags |= SCAN_DONT_KILL_APP;
16702        }
16703        if (instantApp) {
16704            scanFlags |= SCAN_AS_INSTANT_APP;
16705        }
16706        if (fullApp) {
16707            scanFlags |= SCAN_AS_FULL_APP;
16708        }
16709        if (virtualPreload) {
16710            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16711        }
16712
16713        // Result object to be returned
16714        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16715        res.installerPackageName = installerPackageName;
16716
16717        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16718
16719        // Sanity check
16720        if (instantApp && (forwardLocked || onExternal)) {
16721            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16722                    + " external=" + onExternal);
16723            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16724            return;
16725        }
16726
16727        // Retrieve PackageSettings and parse package
16728        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16729                | PackageParser.PARSE_ENFORCE_CODE
16730                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16731                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16732                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16733        PackageParser pp = new PackageParser();
16734        pp.setSeparateProcesses(mSeparateProcesses);
16735        pp.setDisplayMetrics(mMetrics);
16736        pp.setCallback(mPackageParserCallback);
16737
16738        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16739        final PackageParser.Package pkg;
16740        try {
16741            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16742            DexMetadataHelper.validatePackageDexMetadata(pkg);
16743        } catch (PackageParserException e) {
16744            res.setError("Failed parse during installPackageLI", e);
16745            return;
16746        } finally {
16747            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16748        }
16749
16750        // Instant apps have several additional install-time checks.
16751        if (instantApp) {
16752            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
16753                Slog.w(TAG,
16754                        "Instant app package " + pkg.packageName + " does not target at least O");
16755                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16756                        "Instant app package must target at least O");
16757                return;
16758            }
16759            if (pkg.applicationInfo.targetSandboxVersion != 2) {
16760                Slog.w(TAG, "Instant app package " + pkg.packageName
16761                        + " does not target targetSandboxVersion 2");
16762                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16763                        "Instant app package must use targetSandboxVersion 2");
16764                return;
16765            }
16766            if (pkg.mSharedUserId != null) {
16767                Slog.w(TAG, "Instant app package " + pkg.packageName
16768                        + " may not declare sharedUserId.");
16769                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16770                        "Instant app package may not declare a sharedUserId");
16771                return;
16772            }
16773        }
16774
16775        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16776            // Static shared libraries have synthetic package names
16777            renameStaticSharedLibraryPackage(pkg);
16778
16779            // No static shared libs on external storage
16780            if (onExternal) {
16781                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16782                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16783                        "Packages declaring static-shared libs cannot be updated");
16784                return;
16785            }
16786        }
16787
16788        // If we are installing a clustered package add results for the children
16789        if (pkg.childPackages != null) {
16790            synchronized (mPackages) {
16791                final int childCount = pkg.childPackages.size();
16792                for (int i = 0; i < childCount; i++) {
16793                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16794                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16795                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16796                    childRes.pkg = childPkg;
16797                    childRes.name = childPkg.packageName;
16798                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16799                    if (childPs != null) {
16800                        childRes.origUsers = childPs.queryInstalledUsers(
16801                                sUserManager.getUserIds(), true);
16802                    }
16803                    if ((mPackages.containsKey(childPkg.packageName))) {
16804                        childRes.removedInfo = new PackageRemovedInfo(this);
16805                        childRes.removedInfo.removedPackage = childPkg.packageName;
16806                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16807                    }
16808                    if (res.addedChildPackages == null) {
16809                        res.addedChildPackages = new ArrayMap<>();
16810                    }
16811                    res.addedChildPackages.put(childPkg.packageName, childRes);
16812                }
16813            }
16814        }
16815
16816        // If package doesn't declare API override, mark that we have an install
16817        // time CPU ABI override.
16818        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16819            pkg.cpuAbiOverride = args.abiOverride;
16820        }
16821
16822        String pkgName = res.name = pkg.packageName;
16823        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16824            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16825                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16826                return;
16827            }
16828        }
16829
16830        try {
16831            // either use what we've been given or parse directly from the APK
16832            if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
16833                pkg.setSigningDetails(args.signingDetails);
16834            } else {
16835                PackageParser.collectCertificates(pkg, false /* skipVerify */);
16836            }
16837        } catch (PackageParserException e) {
16838            res.setError("Failed collect during installPackageLI", e);
16839            return;
16840        }
16841
16842        if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
16843                < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
16844            Slog.w(TAG, "Instant app package " + pkg.packageName
16845                    + " is not signed with at least APK Signature Scheme v2");
16846            res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16847                    "Instant app package must be signed with APK Signature Scheme v2 or greater");
16848            return;
16849        }
16850
16851        // Get rid of all references to package scan path via parser.
16852        pp = null;
16853        String oldCodePath = null;
16854        boolean systemApp = false;
16855        synchronized (mPackages) {
16856            // Check if installing already existing package
16857            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16858                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16859                if (pkg.mOriginalPackages != null
16860                        && pkg.mOriginalPackages.contains(oldName)
16861                        && mPackages.containsKey(oldName)) {
16862                    // This package is derived from an original package,
16863                    // and this device has been updating from that original
16864                    // name.  We must continue using the original name, so
16865                    // rename the new package here.
16866                    pkg.setPackageName(oldName);
16867                    pkgName = pkg.packageName;
16868                    replace = true;
16869                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16870                            + oldName + " pkgName=" + pkgName);
16871                } else if (mPackages.containsKey(pkgName)) {
16872                    // This package, under its official name, already exists
16873                    // on the device; we should replace it.
16874                    replace = true;
16875                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16876                }
16877
16878                // Child packages are installed through the parent package
16879                if (pkg.parentPackage != null) {
16880                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16881                            "Package " + pkg.packageName + " is child of package "
16882                                    + pkg.parentPackage.parentPackage + ". Child packages "
16883                                    + "can be updated only through the parent package.");
16884                    return;
16885                }
16886
16887                if (replace) {
16888                    // Prevent apps opting out from runtime permissions
16889                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16890                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16891                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16892                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16893                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16894                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16895                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16896                                        + " doesn't support runtime permissions but the old"
16897                                        + " target SDK " + oldTargetSdk + " does.");
16898                        return;
16899                    }
16900                    // Prevent persistent apps from being updated
16901                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
16902                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
16903                                "Package " + oldPackage.packageName + " is a persistent app. "
16904                                        + "Persistent apps are not updateable.");
16905                        return;
16906                    }
16907                    // Prevent apps from downgrading their targetSandbox.
16908                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16909                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16910                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16911                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16912                                "Package " + pkg.packageName + " new target sandbox "
16913                                + newTargetSandbox + " is incompatible with the previous value of"
16914                                + oldTargetSandbox + ".");
16915                        return;
16916                    }
16917
16918                    // Prevent installing of child packages
16919                    if (oldPackage.parentPackage != null) {
16920                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16921                                "Package " + pkg.packageName + " is child of package "
16922                                        + oldPackage.parentPackage + ". Child packages "
16923                                        + "can be updated only through the parent package.");
16924                        return;
16925                    }
16926                }
16927            }
16928
16929            PackageSetting ps = mSettings.mPackages.get(pkgName);
16930            if (ps != null) {
16931                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16932
16933                // Static shared libs have same package with different versions where
16934                // we internally use a synthetic package name to allow multiple versions
16935                // of the same package, therefore we need to compare signatures against
16936                // the package setting for the latest library version.
16937                PackageSetting signatureCheckPs = ps;
16938                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16939                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16940                    if (libraryEntry != null) {
16941                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16942                    }
16943                }
16944
16945                // Quick sanity check that we're signed correctly if updating;
16946                // we'll check this again later when scanning, but we want to
16947                // bail early here before tripping over redefined permissions.
16948                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16949                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
16950                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
16951                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16952                                + pkg.packageName + " upgrade keys do not match the "
16953                                + "previously installed version");
16954                        return;
16955                    }
16956                } else {
16957                    try {
16958                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
16959                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
16960                        // We don't care about disabledPkgSetting on install for now.
16961                        final boolean compatMatch = verifySignatures(
16962                                signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
16963                                compareRecover);
16964                        // The new KeySets will be re-added later in the scanning process.
16965                        if (compatMatch) {
16966                            synchronized (mPackages) {
16967                                ksms.removeAppKeySetDataLPw(pkg.packageName);
16968                            }
16969                        }
16970                    } catch (PackageManagerException e) {
16971                        res.setError(e.error, e.getMessage());
16972                        return;
16973                    }
16974                }
16975
16976                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16977                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16978                    systemApp = (ps.pkg.applicationInfo.flags &
16979                            ApplicationInfo.FLAG_SYSTEM) != 0;
16980                }
16981                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16982            }
16983
16984            int N = pkg.permissions.size();
16985            for (int i = N-1; i >= 0; i--) {
16986                final PackageParser.Permission perm = pkg.permissions.get(i);
16987                final BasePermission bp =
16988                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
16989
16990                // Don't allow anyone but the system to define ephemeral permissions.
16991                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
16992                        && !systemApp) {
16993                    Slog.w(TAG, "Non-System package " + pkg.packageName
16994                            + " attempting to delcare ephemeral permission "
16995                            + perm.info.name + "; Removing ephemeral.");
16996                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
16997                }
16998
16999                // Check whether the newly-scanned package wants to define an already-defined perm
17000                if (bp != null) {
17001                    // If the defining package is signed with our cert, it's okay.  This
17002                    // also includes the "updating the same package" case, of course.
17003                    // "updating same package" could also involve key-rotation.
17004                    final boolean sigsOk;
17005                    final String sourcePackageName = bp.getSourcePackageName();
17006                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17007                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17008                    if (sourcePackageName.equals(pkg.packageName)
17009                            && (ksms.shouldCheckUpgradeKeySetLocked(
17010                                    sourcePackageSetting, scanFlags))) {
17011                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
17012                    } else {
17013
17014                        // in the event of signing certificate rotation, we need to see if the
17015                        // package's certificate has rotated from the current one, or if it is an
17016                        // older certificate with which the current is ok with sharing permissions
17017                        if (sourcePackageSetting.signatures.mSigningDetails.checkCapability(
17018                                        pkg.mSigningDetails,
17019                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17020                            sigsOk = true;
17021                        } else if (pkg.mSigningDetails.checkCapability(
17022                                        sourcePackageSetting.signatures.mSigningDetails,
17023                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17024
17025                            // the scanned package checks out, has signing certificate rotation
17026                            // history, and is newer; bring it over
17027                            sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails;
17028                            sigsOk = true;
17029                        } else {
17030                            sigsOk = false;
17031                        }
17032                    }
17033                    if (!sigsOk) {
17034                        // If the owning package is the system itself, we log but allow
17035                        // install to proceed; we fail the install on all other permission
17036                        // redefinitions.
17037                        if (!sourcePackageName.equals("android")) {
17038                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17039                                    + pkg.packageName + " attempting to redeclare permission "
17040                                    + perm.info.name + " already owned by " + sourcePackageName);
17041                            res.origPermission = perm.info.name;
17042                            res.origPackage = sourcePackageName;
17043                            return;
17044                        } else {
17045                            Slog.w(TAG, "Package " + pkg.packageName
17046                                    + " attempting to redeclare system permission "
17047                                    + perm.info.name + "; ignoring new declaration");
17048                            pkg.permissions.remove(i);
17049                        }
17050                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17051                        // Prevent apps to change protection level to dangerous from any other
17052                        // type as this would allow a privilege escalation where an app adds a
17053                        // normal/signature permission in other app's group and later redefines
17054                        // it as dangerous leading to the group auto-grant.
17055                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17056                                == PermissionInfo.PROTECTION_DANGEROUS) {
17057                            if (bp != null && !bp.isRuntime()) {
17058                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17059                                        + "non-runtime permission " + perm.info.name
17060                                        + " to runtime; keeping old protection level");
17061                                perm.info.protectionLevel = bp.getProtectionLevel();
17062                            }
17063                        }
17064                    }
17065                }
17066            }
17067        }
17068
17069        if (systemApp) {
17070            if (onExternal) {
17071                // Abort update; system app can't be replaced with app on sdcard
17072                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17073                        "Cannot install updates to system apps on sdcard");
17074                return;
17075            } else if (instantApp) {
17076                // Abort update; system app can't be replaced with an instant app
17077                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17078                        "Cannot update a system app with an instant app");
17079                return;
17080            }
17081        }
17082
17083        if (args.move != null) {
17084            // We did an in-place move, so dex is ready to roll
17085            scanFlags |= SCAN_NO_DEX;
17086            scanFlags |= SCAN_MOVE;
17087
17088            synchronized (mPackages) {
17089                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17090                if (ps == null) {
17091                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17092                            "Missing settings for moved package " + pkgName);
17093                }
17094
17095                // We moved the entire application as-is, so bring over the
17096                // previously derived ABI information.
17097                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17098                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17099            }
17100
17101        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17102            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17103            scanFlags |= SCAN_NO_DEX;
17104
17105            try {
17106                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17107                    args.abiOverride : pkg.cpuAbiOverride);
17108                final boolean extractNativeLibs = !pkg.isLibrary();
17109                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
17110            } catch (PackageManagerException pme) {
17111                Slog.e(TAG, "Error deriving application ABI", pme);
17112                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17113                return;
17114            }
17115
17116            // Shared libraries for the package need to be updated.
17117            synchronized (mPackages) {
17118                try {
17119                    updateSharedLibrariesLPr(pkg, null);
17120                } catch (PackageManagerException e) {
17121                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17122                }
17123            }
17124        }
17125
17126        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17127            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17128            return;
17129        }
17130
17131        if (PackageManagerServiceUtils.isApkVerityEnabled()) {
17132            String apkPath = null;
17133            synchronized (mPackages) {
17134                // Note that if the attacker managed to skip verify setup, for example by tampering
17135                // with the package settings, upon reboot we will do full apk verification when
17136                // verity is not detected.
17137                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17138                if (ps != null && ps.isPrivileged()) {
17139                    apkPath = pkg.baseCodePath;
17140                }
17141            }
17142
17143            if (apkPath != null) {
17144                final VerityUtils.SetupResult result =
17145                        VerityUtils.generateApkVeritySetupData(apkPath);
17146                if (result.isOk()) {
17147                    if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath);
17148                    FileDescriptor fd = result.getUnownedFileDescriptor();
17149                    try {
17150                        mInstaller.installApkVerity(apkPath, fd);
17151                    } catch (InstallerException e) {
17152                        res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17153                                "Failed to set up verity: " + e);
17154                        return;
17155                    } finally {
17156                        IoUtils.closeQuietly(fd);
17157                    }
17158                } else if (result.isFailed()) {
17159                    res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity");
17160                    return;
17161                } else {
17162                    // Do nothing if verity is skipped. Will fall back to full apk verification on
17163                    // reboot.
17164                }
17165            }
17166        }
17167
17168        if (!instantApp) {
17169            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17170        } else {
17171            if (DEBUG_DOMAIN_VERIFICATION) {
17172                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17173            }
17174        }
17175
17176        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17177                "installPackageLI")) {
17178            if (replace) {
17179                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17180                    // Static libs have a synthetic package name containing the version
17181                    // and cannot be updated as an update would get a new package name,
17182                    // unless this is the exact same version code which is useful for
17183                    // development.
17184                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17185                    if (existingPkg != null &&
17186                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
17187                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17188                                + "static-shared libs cannot be updated");
17189                        return;
17190                    }
17191                }
17192                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
17193                        installerPackageName, res, args.installReason);
17194            } else {
17195                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17196                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17197            }
17198        }
17199
17200        // Prepare the application profiles for the new code paths.
17201        // This needs to be done before invoking dexopt so that any install-time profile
17202        // can be used for optimizations.
17203        mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier()));
17204
17205        // Check whether we need to dexopt the app.
17206        //
17207        // NOTE: it is IMPORTANT to call dexopt:
17208        //   - after doRename which will sync the package data from PackageParser.Package and its
17209        //     corresponding ApplicationInfo.
17210        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
17211        //     uid of the application (pkg.applicationInfo.uid).
17212        //     This update happens in place!
17213        //
17214        // We only need to dexopt if the package meets ALL of the following conditions:
17215        //   1) it is not forward locked.
17216        //   2) it is not on on an external ASEC container.
17217        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17218        //
17219        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17220        // complete, so we skip this step during installation. Instead, we'll take extra time
17221        // the first time the instant app starts. It's preferred to do it this way to provide
17222        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17223        // middle of running an instant app. The default behaviour can be overridden
17224        // via gservices.
17225        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
17226                && !forwardLocked
17227                && !pkg.applicationInfo.isExternalAsec()
17228                && (!instantApp || Global.getInt(mContext.getContentResolver(),
17229                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
17230
17231        if (performDexopt) {
17232            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17233            // Do not run PackageDexOptimizer through the local performDexOpt
17234            // method because `pkg` may not be in `mPackages` yet.
17235            //
17236            // Also, don't fail application installs if the dexopt step fails.
17237            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17238                    REASON_INSTALL,
17239                    DexoptOptions.DEXOPT_BOOT_COMPLETE |
17240                    DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE);
17241            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17242                    null /* instructionSets */,
17243                    getOrCreateCompilerPackageStats(pkg),
17244                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17245                    dexoptOptions);
17246            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17247        }
17248
17249        // Notify BackgroundDexOptService that the package has been changed.
17250        // If this is an update of a package which used to fail to compile,
17251        // BackgroundDexOptService will remove it from its blacklist.
17252        // TODO: Layering violation
17253        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17254
17255        synchronized (mPackages) {
17256            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17257            if (ps != null) {
17258                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17259                ps.setUpdateAvailable(false /*updateAvailable*/);
17260            }
17261
17262            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17263            for (int i = 0; i < childCount; i++) {
17264                PackageParser.Package childPkg = pkg.childPackages.get(i);
17265                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17266                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17267                if (childPs != null) {
17268                    childRes.newUsers = childPs.queryInstalledUsers(
17269                            sUserManager.getUserIds(), true);
17270                }
17271            }
17272
17273            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17274                updateSequenceNumberLP(ps, res.newUsers);
17275                updateInstantAppInstallerLocked(pkgName);
17276            }
17277        }
17278    }
17279
17280    private void startIntentFilterVerifications(int userId, boolean replacing,
17281            PackageParser.Package pkg) {
17282        if (mIntentFilterVerifierComponent == null) {
17283            Slog.w(TAG, "No IntentFilter verification will not be done as "
17284                    + "there is no IntentFilterVerifier available!");
17285            return;
17286        }
17287
17288        final int verifierUid = getPackageUid(
17289                mIntentFilterVerifierComponent.getPackageName(),
17290                MATCH_DEBUG_TRIAGED_MISSING,
17291                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17292
17293        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17294        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17295        mHandler.sendMessage(msg);
17296
17297        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17298        for (int i = 0; i < childCount; i++) {
17299            PackageParser.Package childPkg = pkg.childPackages.get(i);
17300            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17301            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17302            mHandler.sendMessage(msg);
17303        }
17304    }
17305
17306    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17307            PackageParser.Package pkg) {
17308        int size = pkg.activities.size();
17309        if (size == 0) {
17310            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17311                    "No activity, so no need to verify any IntentFilter!");
17312            return;
17313        }
17314
17315        final boolean hasDomainURLs = hasDomainURLs(pkg);
17316        if (!hasDomainURLs) {
17317            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17318                    "No domain URLs, so no need to verify any IntentFilter!");
17319            return;
17320        }
17321
17322        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17323                + " if any IntentFilter from the " + size
17324                + " Activities needs verification ...");
17325
17326        int count = 0;
17327        final String packageName = pkg.packageName;
17328
17329        synchronized (mPackages) {
17330            // If this is a new install and we see that we've already run verification for this
17331            // package, we have nothing to do: it means the state was restored from backup.
17332            if (!replacing) {
17333                IntentFilterVerificationInfo ivi =
17334                        mSettings.getIntentFilterVerificationLPr(packageName);
17335                if (ivi != null) {
17336                    if (DEBUG_DOMAIN_VERIFICATION) {
17337                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17338                                + ivi.getStatusString());
17339                    }
17340                    return;
17341                }
17342            }
17343
17344            // If any filters need to be verified, then all need to be.
17345            boolean needToVerify = false;
17346            for (PackageParser.Activity a : pkg.activities) {
17347                for (ActivityIntentInfo filter : a.intents) {
17348                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17349                        if (DEBUG_DOMAIN_VERIFICATION) {
17350                            Slog.d(TAG,
17351                                    "Intent filter needs verification, so processing all filters");
17352                        }
17353                        needToVerify = true;
17354                        break;
17355                    }
17356                }
17357            }
17358
17359            if (needToVerify) {
17360                final int verificationId = mIntentFilterVerificationToken++;
17361                for (PackageParser.Activity a : pkg.activities) {
17362                    for (ActivityIntentInfo filter : a.intents) {
17363                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17364                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17365                                    "Verification needed for IntentFilter:" + filter.toString());
17366                            mIntentFilterVerifier.addOneIntentFilterVerification(
17367                                    verifierUid, userId, verificationId, filter, packageName);
17368                            count++;
17369                        }
17370                    }
17371                }
17372            }
17373        }
17374
17375        if (count > 0) {
17376            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17377                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17378                    +  " for userId:" + userId);
17379            mIntentFilterVerifier.startVerifications(userId);
17380        } else {
17381            if (DEBUG_DOMAIN_VERIFICATION) {
17382                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17383            }
17384        }
17385    }
17386
17387    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17388        final ComponentName cn  = filter.activity.getComponentName();
17389        final String packageName = cn.getPackageName();
17390
17391        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17392                packageName);
17393        if (ivi == null) {
17394            return true;
17395        }
17396        int status = ivi.getStatus();
17397        switch (status) {
17398            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17399            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17400                return true;
17401
17402            default:
17403                // Nothing to do
17404                return false;
17405        }
17406    }
17407
17408    private static boolean isMultiArch(ApplicationInfo info) {
17409        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17410    }
17411
17412    private static boolean isExternal(PackageParser.Package pkg) {
17413        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17414    }
17415
17416    private static boolean isExternal(PackageSetting ps) {
17417        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17418    }
17419
17420    private static boolean isSystemApp(PackageParser.Package pkg) {
17421        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17422    }
17423
17424    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17425        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17426    }
17427
17428    private static boolean isOemApp(PackageParser.Package pkg) {
17429        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17430    }
17431
17432    private static boolean isVendorApp(PackageParser.Package pkg) {
17433        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17434    }
17435
17436    private static boolean isProductApp(PackageParser.Package pkg) {
17437        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
17438    }
17439
17440    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17441        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17442    }
17443
17444    private static boolean isSystemApp(PackageSetting ps) {
17445        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17446    }
17447
17448    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17449        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17450    }
17451
17452    private int packageFlagsToInstallFlags(PackageSetting ps) {
17453        int installFlags = 0;
17454        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17455            // This existing package was an external ASEC install when we have
17456            // the external flag without a UUID
17457            installFlags |= PackageManager.INSTALL_EXTERNAL;
17458        }
17459        if (ps.isForwardLocked()) {
17460            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17461        }
17462        return installFlags;
17463    }
17464
17465    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17466        if (isExternal(pkg)) {
17467            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17468                return mSettings.getExternalVersion();
17469            } else {
17470                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17471            }
17472        } else {
17473            return mSettings.getInternalVersion();
17474        }
17475    }
17476
17477    private void deleteTempPackageFiles() {
17478        final FilenameFilter filter = new FilenameFilter() {
17479            public boolean accept(File dir, String name) {
17480                return name.startsWith("vmdl") && name.endsWith(".tmp");
17481            }
17482        };
17483        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17484            file.delete();
17485        }
17486    }
17487
17488    @Override
17489    public void deletePackageAsUser(String packageName, int versionCode,
17490            IPackageDeleteObserver observer, int userId, int flags) {
17491        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17492                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17493    }
17494
17495    @Override
17496    public void deletePackageVersioned(VersionedPackage versionedPackage,
17497            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17498        final int callingUid = Binder.getCallingUid();
17499        mContext.enforceCallingOrSelfPermission(
17500                android.Manifest.permission.DELETE_PACKAGES, null);
17501        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17502        Preconditions.checkNotNull(versionedPackage);
17503        Preconditions.checkNotNull(observer);
17504        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17505                PackageManager.VERSION_CODE_HIGHEST,
17506                Long.MAX_VALUE, "versionCode must be >= -1");
17507
17508        final String packageName = versionedPackage.getPackageName();
17509        final long versionCode = versionedPackage.getLongVersionCode();
17510        final String internalPackageName;
17511        synchronized (mPackages) {
17512            // Normalize package name to handle renamed packages and static libs
17513            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17514        }
17515
17516        final int uid = Binder.getCallingUid();
17517        if (!isOrphaned(internalPackageName)
17518                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17519            try {
17520                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17521                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17522                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17523                observer.onUserActionRequired(intent);
17524            } catch (RemoteException re) {
17525            }
17526            return;
17527        }
17528        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17529        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17530        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17531            mContext.enforceCallingOrSelfPermission(
17532                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17533                    "deletePackage for user " + userId);
17534        }
17535
17536        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17537            try {
17538                observer.onPackageDeleted(packageName,
17539                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17540            } catch (RemoteException re) {
17541            }
17542            return;
17543        }
17544
17545        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17546            try {
17547                observer.onPackageDeleted(packageName,
17548                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17549            } catch (RemoteException re) {
17550            }
17551            return;
17552        }
17553
17554        if (DEBUG_REMOVE) {
17555            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17556                    + " deleteAllUsers: " + deleteAllUsers + " version="
17557                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17558                    ? "VERSION_CODE_HIGHEST" : versionCode));
17559        }
17560        // Queue up an async operation since the package deletion may take a little while.
17561        mHandler.post(new Runnable() {
17562            public void run() {
17563                mHandler.removeCallbacks(this);
17564                int returnCode;
17565                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17566                boolean doDeletePackage = true;
17567                if (ps != null) {
17568                    final boolean targetIsInstantApp =
17569                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17570                    doDeletePackage = !targetIsInstantApp
17571                            || canViewInstantApps;
17572                }
17573                if (doDeletePackage) {
17574                    if (!deleteAllUsers) {
17575                        returnCode = deletePackageX(internalPackageName, versionCode,
17576                                userId, deleteFlags);
17577                    } else {
17578                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17579                                internalPackageName, users);
17580                        // If nobody is blocking uninstall, proceed with delete for all users
17581                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17582                            returnCode = deletePackageX(internalPackageName, versionCode,
17583                                    userId, deleteFlags);
17584                        } else {
17585                            // Otherwise uninstall individually for users with blockUninstalls=false
17586                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17587                            for (int userId : users) {
17588                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17589                                    returnCode = deletePackageX(internalPackageName, versionCode,
17590                                            userId, userFlags);
17591                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17592                                        Slog.w(TAG, "Package delete failed for user " + userId
17593                                                + ", returnCode " + returnCode);
17594                                    }
17595                                }
17596                            }
17597                            // The app has only been marked uninstalled for certain users.
17598                            // We still need to report that delete was blocked
17599                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17600                        }
17601                    }
17602                } else {
17603                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17604                }
17605                try {
17606                    observer.onPackageDeleted(packageName, returnCode, null);
17607                } catch (RemoteException e) {
17608                    Log.i(TAG, "Observer no longer exists.");
17609                } //end catch
17610            } //end run
17611        });
17612    }
17613
17614    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17615        if (pkg.staticSharedLibName != null) {
17616            return pkg.manifestPackageName;
17617        }
17618        return pkg.packageName;
17619    }
17620
17621    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17622        // Handle renamed packages
17623        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17624        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17625
17626        // Is this a static library?
17627        LongSparseArray<SharedLibraryEntry> versionedLib =
17628                mStaticLibsByDeclaringPackage.get(packageName);
17629        if (versionedLib == null || versionedLib.size() <= 0) {
17630            return packageName;
17631        }
17632
17633        // Figure out which lib versions the caller can see
17634        LongSparseLongArray versionsCallerCanSee = null;
17635        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17636        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17637                && callingAppId != Process.ROOT_UID) {
17638            versionsCallerCanSee = new LongSparseLongArray();
17639            String libName = versionedLib.valueAt(0).info.getName();
17640            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17641            if (uidPackages != null) {
17642                for (String uidPackage : uidPackages) {
17643                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17644                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17645                    if (libIdx >= 0) {
17646                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17647                        versionsCallerCanSee.append(libVersion, libVersion);
17648                    }
17649                }
17650            }
17651        }
17652
17653        // Caller can see nothing - done
17654        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17655            return packageName;
17656        }
17657
17658        // Find the version the caller can see and the app version code
17659        SharedLibraryEntry highestVersion = null;
17660        final int versionCount = versionedLib.size();
17661        for (int i = 0; i < versionCount; i++) {
17662            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17663            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17664                    libEntry.info.getLongVersion()) < 0) {
17665                continue;
17666            }
17667            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17668            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17669                if (libVersionCode == versionCode) {
17670                    return libEntry.apk;
17671                }
17672            } else if (highestVersion == null) {
17673                highestVersion = libEntry;
17674            } else if (libVersionCode  > highestVersion.info
17675                    .getDeclaringPackage().getLongVersionCode()) {
17676                highestVersion = libEntry;
17677            }
17678        }
17679
17680        if (highestVersion != null) {
17681            return highestVersion.apk;
17682        }
17683
17684        return packageName;
17685    }
17686
17687    boolean isCallerVerifier(int callingUid) {
17688        final int callingUserId = UserHandle.getUserId(callingUid);
17689        return mRequiredVerifierPackage != null &&
17690                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17691    }
17692
17693    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17694        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17695              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17696            return true;
17697        }
17698        final int callingUserId = UserHandle.getUserId(callingUid);
17699        // If the caller installed the pkgName, then allow it to silently uninstall.
17700        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17701            return true;
17702        }
17703
17704        // Allow package verifier to silently uninstall.
17705        if (mRequiredVerifierPackage != null &&
17706                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17707            return true;
17708        }
17709
17710        // Allow package uninstaller to silently uninstall.
17711        if (mRequiredUninstallerPackage != null &&
17712                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17713            return true;
17714        }
17715
17716        // Allow storage manager to silently uninstall.
17717        if (mStorageManagerPackage != null &&
17718                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17719            return true;
17720        }
17721
17722        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17723        // uninstall for device owner provisioning.
17724        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17725                == PERMISSION_GRANTED) {
17726            return true;
17727        }
17728
17729        return false;
17730    }
17731
17732    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17733        int[] result = EMPTY_INT_ARRAY;
17734        for (int userId : userIds) {
17735            if (getBlockUninstallForUser(packageName, userId)) {
17736                result = ArrayUtils.appendInt(result, userId);
17737            }
17738        }
17739        return result;
17740    }
17741
17742    @Override
17743    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17744        final int callingUid = Binder.getCallingUid();
17745        if (getInstantAppPackageName(callingUid) != null
17746                && !isCallerSameApp(packageName, callingUid)) {
17747            return false;
17748        }
17749        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17750    }
17751
17752    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17753        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17754                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17755        try {
17756            if (dpm != null) {
17757                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17758                        /* callingUserOnly =*/ false);
17759                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17760                        : deviceOwnerComponentName.getPackageName();
17761                // Does the package contains the device owner?
17762                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17763                // this check is probably not needed, since DO should be registered as a device
17764                // admin on some user too. (Original bug for this: b/17657954)
17765                if (packageName.equals(deviceOwnerPackageName)) {
17766                    return true;
17767                }
17768                // Does it contain a device admin for any user?
17769                int[] users;
17770                if (userId == UserHandle.USER_ALL) {
17771                    users = sUserManager.getUserIds();
17772                } else {
17773                    users = new int[]{userId};
17774                }
17775                for (int i = 0; i < users.length; ++i) {
17776                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17777                        return true;
17778                    }
17779                }
17780            }
17781        } catch (RemoteException e) {
17782        }
17783        return false;
17784    }
17785
17786    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17787        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17788    }
17789
17790    /**
17791     *  This method is an internal method that could be get invoked either
17792     *  to delete an installed package or to clean up a failed installation.
17793     *  After deleting an installed package, a broadcast is sent to notify any
17794     *  listeners that the package has been removed. For cleaning up a failed
17795     *  installation, the broadcast is not necessary since the package's
17796     *  installation wouldn't have sent the initial broadcast either
17797     *  The key steps in deleting a package are
17798     *  deleting the package information in internal structures like mPackages,
17799     *  deleting the packages base directories through installd
17800     *  updating mSettings to reflect current status
17801     *  persisting settings for later use
17802     *  sending a broadcast if necessary
17803     */
17804    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
17805        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17806        final boolean res;
17807
17808        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17809                ? UserHandle.USER_ALL : userId;
17810
17811        if (isPackageDeviceAdmin(packageName, removeUser)) {
17812            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17813            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17814        }
17815
17816        PackageSetting uninstalledPs = null;
17817        PackageParser.Package pkg = null;
17818
17819        // for the uninstall-updates case and restricted profiles, remember the per-
17820        // user handle installed state
17821        int[] allUsers;
17822        synchronized (mPackages) {
17823            uninstalledPs = mSettings.mPackages.get(packageName);
17824            if (uninstalledPs == null) {
17825                Slog.w(TAG, "Not removing non-existent package " + packageName);
17826                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17827            }
17828
17829            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17830                    && uninstalledPs.versionCode != versionCode) {
17831                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17832                        + uninstalledPs.versionCode + " != " + versionCode);
17833                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17834            }
17835
17836            // Static shared libs can be declared by any package, so let us not
17837            // allow removing a package if it provides a lib others depend on.
17838            pkg = mPackages.get(packageName);
17839
17840            allUsers = sUserManager.getUserIds();
17841
17842            if (pkg != null && pkg.staticSharedLibName != null) {
17843                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17844                        pkg.staticSharedLibVersion);
17845                if (libEntry != null) {
17846                    for (int currUserId : allUsers) {
17847                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
17848                            continue;
17849                        }
17850                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17851                                libEntry.info, 0, currUserId);
17852                        if (!ArrayUtils.isEmpty(libClientPackages)) {
17853                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17854                                    + " hosting lib " + libEntry.info.getName() + " version "
17855                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
17856                                    + " for user " + currUserId);
17857                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17858                        }
17859                    }
17860                }
17861            }
17862
17863            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17864        }
17865
17866        final int freezeUser;
17867        if (isUpdatedSystemApp(uninstalledPs)
17868                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17869            // We're downgrading a system app, which will apply to all users, so
17870            // freeze them all during the downgrade
17871            freezeUser = UserHandle.USER_ALL;
17872        } else {
17873            freezeUser = removeUser;
17874        }
17875
17876        synchronized (mInstallLock) {
17877            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17878            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17879                    deleteFlags, "deletePackageX")) {
17880                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17881                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
17882            }
17883            synchronized (mPackages) {
17884                if (res) {
17885                    if (pkg != null) {
17886                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17887                    }
17888                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
17889                    updateInstantAppInstallerLocked(packageName);
17890                }
17891            }
17892        }
17893
17894        if (res) {
17895            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17896            info.sendPackageRemovedBroadcasts(killApp);
17897            info.sendSystemPackageUpdatedBroadcasts();
17898            info.sendSystemPackageAppearedBroadcasts();
17899        }
17900        // Force a gc here.
17901        Runtime.getRuntime().gc();
17902        // Delete the resources here after sending the broadcast to let
17903        // other processes clean up before deleting resources.
17904        if (info.args != null) {
17905            synchronized (mInstallLock) {
17906                info.args.doPostDeleteLI(true);
17907            }
17908        }
17909
17910        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17911    }
17912
17913    static class PackageRemovedInfo {
17914        final PackageSender packageSender;
17915        String removedPackage;
17916        String installerPackageName;
17917        int uid = -1;
17918        int removedAppId = -1;
17919        int[] origUsers;
17920        int[] removedUsers = null;
17921        int[] broadcastUsers = null;
17922        int[] instantUserIds = null;
17923        SparseArray<Integer> installReasons;
17924        boolean isRemovedPackageSystemUpdate = false;
17925        boolean isUpdate;
17926        boolean dataRemoved;
17927        boolean removedForAllUsers;
17928        boolean isStaticSharedLib;
17929        // Clean up resources deleted packages.
17930        InstallArgs args = null;
17931        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17932        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17933
17934        PackageRemovedInfo(PackageSender packageSender) {
17935            this.packageSender = packageSender;
17936        }
17937
17938        void sendPackageRemovedBroadcasts(boolean killApp) {
17939            sendPackageRemovedBroadcastInternal(killApp);
17940            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17941            for (int i = 0; i < childCount; i++) {
17942                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17943                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17944            }
17945        }
17946
17947        void sendSystemPackageUpdatedBroadcasts() {
17948            if (isRemovedPackageSystemUpdate) {
17949                sendSystemPackageUpdatedBroadcastsInternal();
17950                final int childCount = (removedChildPackages != null)
17951                        ? removedChildPackages.size() : 0;
17952                for (int i = 0; i < childCount; i++) {
17953                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17954                    if (childInfo.isRemovedPackageSystemUpdate) {
17955                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17956                    }
17957                }
17958            }
17959        }
17960
17961        void sendSystemPackageAppearedBroadcasts() {
17962            final int packageCount = (appearedChildPackages != null)
17963                    ? appearedChildPackages.size() : 0;
17964            for (int i = 0; i < packageCount; i++) {
17965                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17966                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
17967                    true /*sendBootCompleted*/, false /*startReceiver*/,
17968                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
17969            }
17970        }
17971
17972        private void sendSystemPackageUpdatedBroadcastsInternal() {
17973            Bundle extras = new Bundle(2);
17974            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17975            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17976            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17977                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
17978            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17979                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
17980            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
17981                null, null, 0, removedPackage, null, null, null);
17982            if (installerPackageName != null) {
17983                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17984                        removedPackage, extras, 0 /*flags*/,
17985                        installerPackageName, null, null, null);
17986                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17987                        removedPackage, extras, 0 /*flags*/,
17988                        installerPackageName, null, null, null);
17989            }
17990        }
17991
17992        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17993            // Don't send static shared library removal broadcasts as these
17994            // libs are visible only the the apps that depend on them an one
17995            // cannot remove the library if it has a dependency.
17996            if (isStaticSharedLib) {
17997                return;
17998            }
17999            Bundle extras = new Bundle(2);
18000            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18001            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18002            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18003            if (isUpdate || isRemovedPackageSystemUpdate) {
18004                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18005            }
18006            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18007            if (removedPackage != null) {
18008                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18009                    removedPackage, extras, 0, null /*targetPackage*/, null,
18010                    broadcastUsers, instantUserIds);
18011                if (installerPackageName != null) {
18012                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18013                            removedPackage, extras, 0 /*flags*/,
18014                            installerPackageName, null, broadcastUsers, instantUserIds);
18015                }
18016                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18017                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18018                        removedPackage, extras,
18019                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18020                        null, null, broadcastUsers, instantUserIds);
18021                    packageSender.notifyPackageRemoved(removedPackage);
18022                }
18023            }
18024            if (removedAppId >= 0) {
18025                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18026                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18027                    null, null, broadcastUsers, instantUserIds);
18028            }
18029        }
18030
18031        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18032            removedUsers = userIds;
18033            if (removedUsers == null) {
18034                broadcastUsers = null;
18035                return;
18036            }
18037
18038            broadcastUsers = EMPTY_INT_ARRAY;
18039            instantUserIds = EMPTY_INT_ARRAY;
18040            for (int i = userIds.length - 1; i >= 0; --i) {
18041                final int userId = userIds[i];
18042                if (deletedPackageSetting.getInstantApp(userId)) {
18043                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
18044                } else {
18045                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18046                }
18047            }
18048        }
18049    }
18050
18051    /*
18052     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18053     * flag is not set, the data directory is removed as well.
18054     * make sure this flag is set for partially installed apps. If not its meaningless to
18055     * delete a partially installed application.
18056     */
18057    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18058            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18059        String packageName = ps.name;
18060        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18061        // Retrieve object to delete permissions for shared user later on
18062        final PackageParser.Package deletedPkg;
18063        final PackageSetting deletedPs;
18064        // reader
18065        synchronized (mPackages) {
18066            deletedPkg = mPackages.get(packageName);
18067            deletedPs = mSettings.mPackages.get(packageName);
18068            if (outInfo != null) {
18069                outInfo.removedPackage = packageName;
18070                outInfo.installerPackageName = ps.installerPackageName;
18071                outInfo.isStaticSharedLib = deletedPkg != null
18072                        && deletedPkg.staticSharedLibName != null;
18073                outInfo.populateUsers(deletedPs == null ? null
18074                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18075            }
18076        }
18077
18078        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
18079
18080        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18081            final PackageParser.Package resolvedPkg;
18082            if (deletedPkg != null) {
18083                resolvedPkg = deletedPkg;
18084            } else {
18085                // We don't have a parsed package when it lives on an ejected
18086                // adopted storage device, so fake something together
18087                resolvedPkg = new PackageParser.Package(ps.name);
18088                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18089            }
18090            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18091                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18092            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18093            if (outInfo != null) {
18094                outInfo.dataRemoved = true;
18095            }
18096            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18097        }
18098
18099        int removedAppId = -1;
18100
18101        // writer
18102        synchronized (mPackages) {
18103            boolean installedStateChanged = false;
18104            if (deletedPs != null) {
18105                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18106                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18107                    clearDefaultBrowserIfNeeded(packageName);
18108                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18109                    removedAppId = mSettings.removePackageLPw(packageName);
18110                    if (outInfo != null) {
18111                        outInfo.removedAppId = removedAppId;
18112                    }
18113                    mPermissionManager.updatePermissions(
18114                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
18115                    if (deletedPs.sharedUser != null) {
18116                        // Remove permissions associated with package. Since runtime
18117                        // permissions are per user we have to kill the removed package
18118                        // or packages running under the shared user of the removed
18119                        // package if revoking the permissions requested only by the removed
18120                        // package is successful and this causes a change in gids.
18121                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18122                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18123                                    userId);
18124                            if (userIdToKill == UserHandle.USER_ALL
18125                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18126                                // If gids changed for this user, kill all affected packages.
18127                                mHandler.post(new Runnable() {
18128                                    @Override
18129                                    public void run() {
18130                                        // This has to happen with no lock held.
18131                                        killApplication(deletedPs.name, deletedPs.appId,
18132                                                KILL_APP_REASON_GIDS_CHANGED);
18133                                    }
18134                                });
18135                                break;
18136                            }
18137                        }
18138                    }
18139                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18140                }
18141                // make sure to preserve per-user disabled state if this removal was just
18142                // a downgrade of a system app to the factory package
18143                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18144                    if (DEBUG_REMOVE) {
18145                        Slog.d(TAG, "Propagating install state across downgrade");
18146                    }
18147                    for (int userId : allUserHandles) {
18148                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18149                        if (DEBUG_REMOVE) {
18150                            Slog.d(TAG, "    user " + userId + " => " + installed);
18151                        }
18152                        if (installed != ps.getInstalled(userId)) {
18153                            installedStateChanged = true;
18154                        }
18155                        ps.setInstalled(installed, userId);
18156                    }
18157                }
18158            }
18159            // can downgrade to reader
18160            if (writeSettings) {
18161                // Save settings now
18162                mSettings.writeLPr();
18163            }
18164            if (installedStateChanged) {
18165                mSettings.writeKernelMappingLPr(ps);
18166            }
18167        }
18168        if (removedAppId != -1) {
18169            // A user ID was deleted here. Go through all users and remove it
18170            // from KeyStore.
18171            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18172        }
18173    }
18174
18175    static boolean locationIsPrivileged(String path) {
18176        try {
18177            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
18178            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
18179            final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
18180            return path.startsWith(privilegedAppDir.getCanonicalPath())
18181                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath())
18182                    || path.startsWith(privilegedProductAppDir.getCanonicalPath());
18183        } catch (IOException e) {
18184            Slog.e(TAG, "Unable to access code path " + path);
18185        }
18186        return false;
18187    }
18188
18189    static boolean locationIsOem(String path) {
18190        try {
18191            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
18192        } catch (IOException e) {
18193            Slog.e(TAG, "Unable to access code path " + path);
18194        }
18195        return false;
18196    }
18197
18198    static boolean locationIsVendor(String path) {
18199        try {
18200            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath());
18201        } catch (IOException e) {
18202            Slog.e(TAG, "Unable to access code path " + path);
18203        }
18204        return false;
18205    }
18206
18207    static boolean locationIsProduct(String path) {
18208        try {
18209            return path.startsWith(Environment.getProductDirectory().getCanonicalPath());
18210        } catch (IOException e) {
18211            Slog.e(TAG, "Unable to access code path " + path);
18212        }
18213        return false;
18214    }
18215
18216    /*
18217     * Tries to delete system package.
18218     */
18219    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18220            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18221            boolean writeSettings) {
18222        if (deletedPs.parentPackageName != null) {
18223            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18224            return false;
18225        }
18226
18227        final boolean applyUserRestrictions
18228                = (allUserHandles != null) && (outInfo.origUsers != null);
18229        final PackageSetting disabledPs;
18230        // Confirm if the system package has been updated
18231        // An updated system app can be deleted. This will also have to restore
18232        // the system pkg from system partition
18233        // reader
18234        synchronized (mPackages) {
18235            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18236        }
18237
18238        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18239                + " disabledPs=" + disabledPs);
18240
18241        if (disabledPs == null) {
18242            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18243            return false;
18244        } else if (DEBUG_REMOVE) {
18245            Slog.d(TAG, "Deleting system pkg from data partition");
18246        }
18247
18248        if (DEBUG_REMOVE) {
18249            if (applyUserRestrictions) {
18250                Slog.d(TAG, "Remembering install states:");
18251                for (int userId : allUserHandles) {
18252                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18253                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18254                }
18255            }
18256        }
18257
18258        // Delete the updated package
18259        outInfo.isRemovedPackageSystemUpdate = true;
18260        if (outInfo.removedChildPackages != null) {
18261            final int childCount = (deletedPs.childPackageNames != null)
18262                    ? deletedPs.childPackageNames.size() : 0;
18263            for (int i = 0; i < childCount; i++) {
18264                String childPackageName = deletedPs.childPackageNames.get(i);
18265                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18266                        .contains(childPackageName)) {
18267                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18268                            childPackageName);
18269                    if (childInfo != null) {
18270                        childInfo.isRemovedPackageSystemUpdate = true;
18271                    }
18272                }
18273            }
18274        }
18275
18276        if (disabledPs.versionCode < deletedPs.versionCode) {
18277            // Delete data for downgrades
18278            flags &= ~PackageManager.DELETE_KEEP_DATA;
18279        } else {
18280            // Preserve data by setting flag
18281            flags |= PackageManager.DELETE_KEEP_DATA;
18282        }
18283
18284        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18285                outInfo, writeSettings, disabledPs.pkg);
18286        if (!ret) {
18287            return false;
18288        }
18289
18290        // writer
18291        synchronized (mPackages) {
18292            // NOTE: The system package always needs to be enabled; even if it's for
18293            // a compressed stub. If we don't, installing the system package fails
18294            // during scan [scanning checks the disabled packages]. We will reverse
18295            // this later, after we've "installed" the stub.
18296            // Reinstate the old system package
18297            enableSystemPackageLPw(disabledPs.pkg);
18298            // Remove any native libraries from the upgraded package.
18299            removeNativeBinariesLI(deletedPs);
18300        }
18301
18302        // Install the system package
18303        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18304        try {
18305            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
18306                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18307        } catch (PackageManagerException e) {
18308            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18309                    + e.getMessage());
18310            return false;
18311        } finally {
18312            if (disabledPs.pkg.isStub) {
18313                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18314            }
18315        }
18316        return true;
18317    }
18318
18319    /**
18320     * Installs a package that's already on the system partition.
18321     */
18322    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
18323            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18324            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18325                    throws PackageManagerException {
18326        @ParseFlags int parseFlags =
18327                mDefParseFlags
18328                | PackageParser.PARSE_MUST_BE_APK
18329                | PackageParser.PARSE_IS_SYSTEM_DIR;
18330        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
18331        if (isPrivileged || locationIsPrivileged(codePathString)) {
18332            scanFlags |= SCAN_AS_PRIVILEGED;
18333        }
18334        if (locationIsOem(codePathString)) {
18335            scanFlags |= SCAN_AS_OEM;
18336        }
18337        if (locationIsVendor(codePathString)) {
18338            scanFlags |= SCAN_AS_VENDOR;
18339        }
18340        if (locationIsProduct(codePathString)) {
18341            scanFlags |= SCAN_AS_PRODUCT;
18342        }
18343
18344        final File codePath = new File(codePathString);
18345        final PackageParser.Package pkg =
18346                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
18347
18348        try {
18349            // update shared libraries for the newly re-installed system package
18350            updateSharedLibrariesLPr(pkg, null);
18351        } catch (PackageManagerException e) {
18352            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18353        }
18354
18355        prepareAppDataAfterInstallLIF(pkg);
18356
18357        // writer
18358        synchronized (mPackages) {
18359            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18360
18361            // Propagate the permissions state as we do not want to drop on the floor
18362            // runtime permissions. The update permissions method below will take
18363            // care of removing obsolete permissions and grant install permissions.
18364            if (origPermissionState != null) {
18365                ps.getPermissionsState().copyFrom(origPermissionState);
18366            }
18367            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18368                    mPermissionCallback);
18369
18370            final boolean applyUserRestrictions
18371                    = (allUserHandles != null) && (origUserHandles != null);
18372            if (applyUserRestrictions) {
18373                boolean installedStateChanged = false;
18374                if (DEBUG_REMOVE) {
18375                    Slog.d(TAG, "Propagating install state across reinstall");
18376                }
18377                for (int userId : allUserHandles) {
18378                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18379                    if (DEBUG_REMOVE) {
18380                        Slog.d(TAG, "    user " + userId + " => " + installed);
18381                    }
18382                    if (installed != ps.getInstalled(userId)) {
18383                        installedStateChanged = true;
18384                    }
18385                    ps.setInstalled(installed, userId);
18386
18387                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18388                }
18389                // Regardless of writeSettings we need to ensure that this restriction
18390                // state propagation is persisted
18391                mSettings.writeAllUsersPackageRestrictionsLPr();
18392                if (installedStateChanged) {
18393                    mSettings.writeKernelMappingLPr(ps);
18394                }
18395            }
18396            // can downgrade to reader here
18397            if (writeSettings) {
18398                mSettings.writeLPr();
18399            }
18400        }
18401        return pkg;
18402    }
18403
18404    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18405            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18406            PackageRemovedInfo outInfo, boolean writeSettings,
18407            PackageParser.Package replacingPackage) {
18408        synchronized (mPackages) {
18409            if (outInfo != null) {
18410                outInfo.uid = ps.appId;
18411            }
18412
18413            if (outInfo != null && outInfo.removedChildPackages != null) {
18414                final int childCount = (ps.childPackageNames != null)
18415                        ? ps.childPackageNames.size() : 0;
18416                for (int i = 0; i < childCount; i++) {
18417                    String childPackageName = ps.childPackageNames.get(i);
18418                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18419                    if (childPs == null) {
18420                        return false;
18421                    }
18422                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18423                            childPackageName);
18424                    if (childInfo != null) {
18425                        childInfo.uid = childPs.appId;
18426                    }
18427                }
18428            }
18429        }
18430
18431        // Delete package data from internal structures and also remove data if flag is set
18432        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18433
18434        // Delete the child packages data
18435        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18436        for (int i = 0; i < childCount; i++) {
18437            PackageSetting childPs;
18438            synchronized (mPackages) {
18439                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18440            }
18441            if (childPs != null) {
18442                PackageRemovedInfo childOutInfo = (outInfo != null
18443                        && outInfo.removedChildPackages != null)
18444                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18445                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18446                        && (replacingPackage != null
18447                        && !replacingPackage.hasChildPackage(childPs.name))
18448                        ? flags & ~DELETE_KEEP_DATA : flags;
18449                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18450                        deleteFlags, writeSettings);
18451            }
18452        }
18453
18454        // Delete application code and resources only for parent packages
18455        if (ps.parentPackageName == null) {
18456            if (deleteCodeAndResources && (outInfo != null)) {
18457                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18458                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18459                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18460            }
18461        }
18462
18463        return true;
18464    }
18465
18466    @Override
18467    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18468            int userId) {
18469        mContext.enforceCallingOrSelfPermission(
18470                android.Manifest.permission.DELETE_PACKAGES, null);
18471        synchronized (mPackages) {
18472            // Cannot block uninstall of static shared libs as they are
18473            // considered a part of the using app (emulating static linking).
18474            // Also static libs are installed always on internal storage.
18475            PackageParser.Package pkg = mPackages.get(packageName);
18476            if (pkg != null && pkg.staticSharedLibName != null) {
18477                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18478                        + " providing static shared library: " + pkg.staticSharedLibName);
18479                return false;
18480            }
18481            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18482            mSettings.writePackageRestrictionsLPr(userId);
18483        }
18484        return true;
18485    }
18486
18487    @Override
18488    public boolean getBlockUninstallForUser(String packageName, int userId) {
18489        synchronized (mPackages) {
18490            final PackageSetting ps = mSettings.mPackages.get(packageName);
18491            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18492                return false;
18493            }
18494            return mSettings.getBlockUninstallLPr(userId, packageName);
18495        }
18496    }
18497
18498    @Override
18499    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18500        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18501        synchronized (mPackages) {
18502            PackageSetting ps = mSettings.mPackages.get(packageName);
18503            if (ps == null) {
18504                Log.w(TAG, "Package doesn't exist: " + packageName);
18505                return false;
18506            }
18507            if (systemUserApp) {
18508                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18509            } else {
18510                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18511            }
18512            mSettings.writeLPr();
18513        }
18514        return true;
18515    }
18516
18517    /*
18518     * This method handles package deletion in general
18519     */
18520    private boolean deletePackageLIF(String packageName, UserHandle user,
18521            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18522            PackageRemovedInfo outInfo, boolean writeSettings,
18523            PackageParser.Package replacingPackage) {
18524        if (packageName == null) {
18525            Slog.w(TAG, "Attempt to delete null packageName.");
18526            return false;
18527        }
18528
18529        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18530
18531        PackageSetting ps;
18532        synchronized (mPackages) {
18533            ps = mSettings.mPackages.get(packageName);
18534            if (ps == null) {
18535                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18536                return false;
18537            }
18538
18539            if (ps.parentPackageName != null && (!isSystemApp(ps)
18540                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18541                if (DEBUG_REMOVE) {
18542                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18543                            + ((user == null) ? UserHandle.USER_ALL : user));
18544                }
18545                final int removedUserId = (user != null) ? user.getIdentifier()
18546                        : UserHandle.USER_ALL;
18547                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18548                    return false;
18549                }
18550                markPackageUninstalledForUserLPw(ps, user);
18551                scheduleWritePackageRestrictionsLocked(user);
18552                return true;
18553            }
18554        }
18555
18556        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18557                && user.getIdentifier() != UserHandle.USER_ALL)) {
18558            // The caller is asking that the package only be deleted for a single
18559            // user.  To do this, we just mark its uninstalled state and delete
18560            // its data. If this is a system app, we only allow this to happen if
18561            // they have set the special DELETE_SYSTEM_APP which requests different
18562            // semantics than normal for uninstalling system apps.
18563            markPackageUninstalledForUserLPw(ps, user);
18564
18565            if (!isSystemApp(ps)) {
18566                // Do not uninstall the APK if an app should be cached
18567                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18568                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18569                    // Other user still have this package installed, so all
18570                    // we need to do is clear this user's data and save that
18571                    // it is uninstalled.
18572                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18573                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18574                        return false;
18575                    }
18576                    scheduleWritePackageRestrictionsLocked(user);
18577                    return true;
18578                } else {
18579                    // We need to set it back to 'installed' so the uninstall
18580                    // broadcasts will be sent correctly.
18581                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18582                    ps.setInstalled(true, user.getIdentifier());
18583                    mSettings.writeKernelMappingLPr(ps);
18584                }
18585            } else {
18586                // This is a system app, so we assume that the
18587                // other users still have this package installed, so all
18588                // we need to do is clear this user's data and save that
18589                // it is uninstalled.
18590                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18591                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18592                    return false;
18593                }
18594                scheduleWritePackageRestrictionsLocked(user);
18595                return true;
18596            }
18597        }
18598
18599        // If we are deleting a composite package for all users, keep track
18600        // of result for each child.
18601        if (ps.childPackageNames != null && outInfo != null) {
18602            synchronized (mPackages) {
18603                final int childCount = ps.childPackageNames.size();
18604                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18605                for (int i = 0; i < childCount; i++) {
18606                    String childPackageName = ps.childPackageNames.get(i);
18607                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18608                    childInfo.removedPackage = childPackageName;
18609                    childInfo.installerPackageName = ps.installerPackageName;
18610                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18611                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18612                    if (childPs != null) {
18613                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18614                    }
18615                }
18616            }
18617        }
18618
18619        boolean ret = false;
18620        if (isSystemApp(ps)) {
18621            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18622            // When an updated system application is deleted we delete the existing resources
18623            // as well and fall back to existing code in system partition
18624            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18625        } else {
18626            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18627            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18628                    outInfo, writeSettings, replacingPackage);
18629        }
18630
18631        // Take a note whether we deleted the package for all users
18632        if (outInfo != null) {
18633            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18634            if (outInfo.removedChildPackages != null) {
18635                synchronized (mPackages) {
18636                    final int childCount = outInfo.removedChildPackages.size();
18637                    for (int i = 0; i < childCount; i++) {
18638                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18639                        if (childInfo != null) {
18640                            childInfo.removedForAllUsers = mPackages.get(
18641                                    childInfo.removedPackage) == null;
18642                        }
18643                    }
18644                }
18645            }
18646            // If we uninstalled an update to a system app there may be some
18647            // child packages that appeared as they are declared in the system
18648            // app but were not declared in the update.
18649            if (isSystemApp(ps)) {
18650                synchronized (mPackages) {
18651                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18652                    final int childCount = (updatedPs.childPackageNames != null)
18653                            ? updatedPs.childPackageNames.size() : 0;
18654                    for (int i = 0; i < childCount; i++) {
18655                        String childPackageName = updatedPs.childPackageNames.get(i);
18656                        if (outInfo.removedChildPackages == null
18657                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18658                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18659                            if (childPs == null) {
18660                                continue;
18661                            }
18662                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18663                            installRes.name = childPackageName;
18664                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18665                            installRes.pkg = mPackages.get(childPackageName);
18666                            installRes.uid = childPs.pkg.applicationInfo.uid;
18667                            if (outInfo.appearedChildPackages == null) {
18668                                outInfo.appearedChildPackages = new ArrayMap<>();
18669                            }
18670                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18671                        }
18672                    }
18673                }
18674            }
18675        }
18676
18677        return ret;
18678    }
18679
18680    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18681        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18682                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18683        for (int nextUserId : userIds) {
18684            if (DEBUG_REMOVE) {
18685                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18686            }
18687            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18688                    false /*installed*/,
18689                    true /*stopped*/,
18690                    true /*notLaunched*/,
18691                    false /*hidden*/,
18692                    false /*suspended*/,
18693                    false /*instantApp*/,
18694                    false /*virtualPreload*/,
18695                    null /*lastDisableAppCaller*/,
18696                    null /*enabledComponents*/,
18697                    null /*disabledComponents*/,
18698                    ps.readUserState(nextUserId).domainVerificationStatus,
18699                    0, PackageManager.INSTALL_REASON_UNKNOWN,
18700                    null /*harmfulAppWarning*/);
18701        }
18702        mSettings.writeKernelMappingLPr(ps);
18703    }
18704
18705    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18706            PackageRemovedInfo outInfo) {
18707        final PackageParser.Package pkg;
18708        synchronized (mPackages) {
18709            pkg = mPackages.get(ps.name);
18710        }
18711
18712        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18713                : new int[] {userId};
18714        for (int nextUserId : userIds) {
18715            if (DEBUG_REMOVE) {
18716                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18717                        + nextUserId);
18718            }
18719
18720            destroyAppDataLIF(pkg, userId,
18721                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18722            destroyAppProfilesLIF(pkg, userId);
18723            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18724            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18725            schedulePackageCleaning(ps.name, nextUserId, false);
18726            synchronized (mPackages) {
18727                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18728                    scheduleWritePackageRestrictionsLocked(nextUserId);
18729                }
18730                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18731            }
18732        }
18733
18734        if (outInfo != null) {
18735            outInfo.removedPackage = ps.name;
18736            outInfo.installerPackageName = ps.installerPackageName;
18737            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18738            outInfo.removedAppId = ps.appId;
18739            outInfo.removedUsers = userIds;
18740            outInfo.broadcastUsers = userIds;
18741        }
18742
18743        return true;
18744    }
18745
18746    private static final class ClearStorageConnection implements ServiceConnection {
18747        IMediaContainerService mContainerService;
18748
18749        @Override
18750        public void onServiceConnected(ComponentName name, IBinder service) {
18751            synchronized (this) {
18752                mContainerService = IMediaContainerService.Stub
18753                        .asInterface(Binder.allowBlocking(service));
18754                notifyAll();
18755            }
18756        }
18757
18758        @Override
18759        public void onServiceDisconnected(ComponentName name) {
18760        }
18761    }
18762
18763    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18764        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18765
18766        final boolean mounted;
18767        if (Environment.isExternalStorageEmulated()) {
18768            mounted = true;
18769        } else {
18770            final String status = Environment.getExternalStorageState();
18771
18772            mounted = status.equals(Environment.MEDIA_MOUNTED)
18773                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18774        }
18775
18776        if (!mounted) {
18777            return;
18778        }
18779
18780        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18781        int[] users;
18782        if (userId == UserHandle.USER_ALL) {
18783            users = sUserManager.getUserIds();
18784        } else {
18785            users = new int[] { userId };
18786        }
18787        final ClearStorageConnection conn = new ClearStorageConnection();
18788        if (mContext.bindServiceAsUser(
18789                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18790            try {
18791                for (int curUser : users) {
18792                    long timeout = SystemClock.uptimeMillis() + 5000;
18793                    synchronized (conn) {
18794                        long now;
18795                        while (conn.mContainerService == null &&
18796                                (now = SystemClock.uptimeMillis()) < timeout) {
18797                            try {
18798                                conn.wait(timeout - now);
18799                            } catch (InterruptedException e) {
18800                            }
18801                        }
18802                    }
18803                    if (conn.mContainerService == null) {
18804                        return;
18805                    }
18806
18807                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18808                    clearDirectory(conn.mContainerService,
18809                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18810                    if (allData) {
18811                        clearDirectory(conn.mContainerService,
18812                                userEnv.buildExternalStorageAppDataDirs(packageName));
18813                        clearDirectory(conn.mContainerService,
18814                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18815                    }
18816                }
18817            } finally {
18818                mContext.unbindService(conn);
18819            }
18820        }
18821    }
18822
18823    @Override
18824    public void clearApplicationProfileData(String packageName) {
18825        enforceSystemOrRoot("Only the system can clear all profile data");
18826
18827        final PackageParser.Package pkg;
18828        synchronized (mPackages) {
18829            pkg = mPackages.get(packageName);
18830        }
18831
18832        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18833            synchronized (mInstallLock) {
18834                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18835            }
18836        }
18837    }
18838
18839    @Override
18840    public void clearApplicationUserData(final String packageName,
18841            final IPackageDataObserver observer, final int userId) {
18842        mContext.enforceCallingOrSelfPermission(
18843                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18844
18845        final int callingUid = Binder.getCallingUid();
18846        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18847                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18848
18849        final PackageSetting ps = mSettings.getPackageLPr(packageName);
18850        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
18851        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18852            throw new SecurityException("Cannot clear data for a protected package: "
18853                    + packageName);
18854        }
18855        // Queue up an async operation since the package deletion may take a little while.
18856        mHandler.post(new Runnable() {
18857            public void run() {
18858                mHandler.removeCallbacks(this);
18859                final boolean succeeded;
18860                if (!filterApp) {
18861                    try (PackageFreezer freezer = freezePackage(packageName,
18862                            "clearApplicationUserData")) {
18863                        synchronized (mInstallLock) {
18864                            succeeded = clearApplicationUserDataLIF(packageName, userId);
18865                        }
18866                        clearExternalStorageDataSync(packageName, userId, true);
18867                        synchronized (mPackages) {
18868                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18869                                    packageName, userId);
18870                        }
18871                    }
18872                    if (succeeded) {
18873                        // invoke DeviceStorageMonitor's update method to clear any notifications
18874                        DeviceStorageMonitorInternal dsm = LocalServices
18875                                .getService(DeviceStorageMonitorInternal.class);
18876                        if (dsm != null) {
18877                            dsm.checkMemory();
18878                        }
18879                    }
18880                } else {
18881                    succeeded = false;
18882                }
18883                if (observer != null) {
18884                    try {
18885                        observer.onRemoveCompleted(packageName, succeeded);
18886                    } catch (RemoteException e) {
18887                        Log.i(TAG, "Observer no longer exists.");
18888                    }
18889                } //end if observer
18890            } //end run
18891        });
18892    }
18893
18894    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18895        if (packageName == null) {
18896            Slog.w(TAG, "Attempt to delete null packageName.");
18897            return false;
18898        }
18899
18900        // Try finding details about the requested package
18901        PackageParser.Package pkg;
18902        synchronized (mPackages) {
18903            pkg = mPackages.get(packageName);
18904            if (pkg == null) {
18905                final PackageSetting ps = mSettings.mPackages.get(packageName);
18906                if (ps != null) {
18907                    pkg = ps.pkg;
18908                }
18909            }
18910
18911            if (pkg == null) {
18912                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18913                return false;
18914            }
18915
18916            PackageSetting ps = (PackageSetting) pkg.mExtras;
18917            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18918        }
18919
18920        clearAppDataLIF(pkg, userId,
18921                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18922
18923        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18924        removeKeystoreDataIfNeeded(userId, appId);
18925
18926        UserManagerInternal umInternal = getUserManagerInternal();
18927        final int flags;
18928        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18929            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18930        } else if (umInternal.isUserRunning(userId)) {
18931            flags = StorageManager.FLAG_STORAGE_DE;
18932        } else {
18933            flags = 0;
18934        }
18935        prepareAppDataContentsLIF(pkg, userId, flags);
18936
18937        return true;
18938    }
18939
18940    /**
18941     * Reverts user permission state changes (permissions and flags) in
18942     * all packages for a given user.
18943     *
18944     * @param userId The device user for which to do a reset.
18945     */
18946    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18947        final int packageCount = mPackages.size();
18948        for (int i = 0; i < packageCount; i++) {
18949            PackageParser.Package pkg = mPackages.valueAt(i);
18950            PackageSetting ps = (PackageSetting) pkg.mExtras;
18951            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18952        }
18953    }
18954
18955    private void resetNetworkPolicies(int userId) {
18956        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18957    }
18958
18959    /**
18960     * Reverts user permission state changes (permissions and flags).
18961     *
18962     * @param ps The package for which to reset.
18963     * @param userId The device user for which to do a reset.
18964     */
18965    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18966            final PackageSetting ps, final int userId) {
18967        if (ps.pkg == null) {
18968            return;
18969        }
18970
18971        // These are flags that can change base on user actions.
18972        final int userSettableMask = FLAG_PERMISSION_USER_SET
18973                | FLAG_PERMISSION_USER_FIXED
18974                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18975                | FLAG_PERMISSION_REVIEW_REQUIRED;
18976
18977        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18978                | FLAG_PERMISSION_POLICY_FIXED;
18979
18980        boolean writeInstallPermissions = false;
18981        boolean writeRuntimePermissions = false;
18982
18983        final int permissionCount = ps.pkg.requestedPermissions.size();
18984        for (int i = 0; i < permissionCount; i++) {
18985            final String permName = ps.pkg.requestedPermissions.get(i);
18986            final BasePermission bp =
18987                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
18988            if (bp == null) {
18989                continue;
18990            }
18991
18992            // If shared user we just reset the state to which only this app contributed.
18993            if (ps.sharedUser != null) {
18994                boolean used = false;
18995                final int packageCount = ps.sharedUser.packages.size();
18996                for (int j = 0; j < packageCount; j++) {
18997                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18998                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18999                            && pkg.pkg.requestedPermissions.contains(permName)) {
19000                        used = true;
19001                        break;
19002                    }
19003                }
19004                if (used) {
19005                    continue;
19006                }
19007            }
19008
19009            final PermissionsState permissionsState = ps.getPermissionsState();
19010
19011            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19012
19013            // Always clear the user settable flags.
19014            final boolean hasInstallState =
19015                    permissionsState.getInstallPermissionState(permName) != null;
19016            // If permission review is enabled and this is a legacy app, mark the
19017            // permission as requiring a review as this is the initial state.
19018            int flags = 0;
19019            if (mSettings.mPermissions.mPermissionReviewRequired
19020                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19021                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19022            }
19023            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19024                if (hasInstallState) {
19025                    writeInstallPermissions = true;
19026                } else {
19027                    writeRuntimePermissions = true;
19028                }
19029            }
19030
19031            // Below is only runtime permission handling.
19032            if (!bp.isRuntime()) {
19033                continue;
19034            }
19035
19036            // Never clobber system or policy.
19037            if ((oldFlags & policyOrSystemFlags) != 0) {
19038                continue;
19039            }
19040
19041            // If this permission was granted by default, make sure it is.
19042            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19043                if (permissionsState.grantRuntimePermission(bp, userId)
19044                        != PERMISSION_OPERATION_FAILURE) {
19045                    writeRuntimePermissions = true;
19046                }
19047            // If permission review is enabled the permissions for a legacy apps
19048            // are represented as constantly granted runtime ones, so don't revoke.
19049            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19050                // Otherwise, reset the permission.
19051                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19052                switch (revokeResult) {
19053                    case PERMISSION_OPERATION_SUCCESS:
19054                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19055                        writeRuntimePermissions = true;
19056                        final int appId = ps.appId;
19057                        mHandler.post(new Runnable() {
19058                            @Override
19059                            public void run() {
19060                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19061                            }
19062                        });
19063                    } break;
19064                }
19065            }
19066        }
19067
19068        // Synchronously write as we are taking permissions away.
19069        if (writeRuntimePermissions) {
19070            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19071        }
19072
19073        // Synchronously write as we are taking permissions away.
19074        if (writeInstallPermissions) {
19075            mSettings.writeLPr();
19076        }
19077    }
19078
19079    /**
19080     * Remove entries from the keystore daemon. Will only remove it if the
19081     * {@code appId} is valid.
19082     */
19083    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19084        if (appId < 0) {
19085            return;
19086        }
19087
19088        final KeyStore keyStore = KeyStore.getInstance();
19089        if (keyStore != null) {
19090            if (userId == UserHandle.USER_ALL) {
19091                for (final int individual : sUserManager.getUserIds()) {
19092                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19093                }
19094            } else {
19095                keyStore.clearUid(UserHandle.getUid(userId, appId));
19096            }
19097        } else {
19098            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19099        }
19100    }
19101
19102    @Override
19103    public void deleteApplicationCacheFiles(final String packageName,
19104            final IPackageDataObserver observer) {
19105        final int userId = UserHandle.getCallingUserId();
19106        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19107    }
19108
19109    @Override
19110    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19111            final IPackageDataObserver observer) {
19112        final int callingUid = Binder.getCallingUid();
19113        if (mContext.checkCallingOrSelfPermission(
19114                android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES)
19115                != PackageManager.PERMISSION_GRANTED) {
19116            // If the caller has the old delete cache permission, silently ignore.  Else throw.
19117            if (mContext.checkCallingOrSelfPermission(
19118                    android.Manifest.permission.DELETE_CACHE_FILES)
19119                    == PackageManager.PERMISSION_GRANTED) {
19120                Slog.w(TAG, "Calling uid " + callingUid + " does not have " +
19121                        android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES +
19122                        ", silently ignoring");
19123                return;
19124            }
19125            mContext.enforceCallingOrSelfPermission(
19126                    android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES, null);
19127        }
19128        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19129                /* requireFullPermission= */ true, /* checkShell= */ false,
19130                "delete application cache files");
19131        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19132                android.Manifest.permission.ACCESS_INSTANT_APPS);
19133
19134        final PackageParser.Package pkg;
19135        synchronized (mPackages) {
19136            pkg = mPackages.get(packageName);
19137        }
19138
19139        // Queue up an async operation since the package deletion may take a little while.
19140        mHandler.post(new Runnable() {
19141            public void run() {
19142                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19143                boolean doClearData = true;
19144                if (ps != null) {
19145                    final boolean targetIsInstantApp =
19146                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19147                    doClearData = !targetIsInstantApp
19148                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19149                }
19150                if (doClearData) {
19151                    synchronized (mInstallLock) {
19152                        final int flags = StorageManager.FLAG_STORAGE_DE
19153                                | StorageManager.FLAG_STORAGE_CE;
19154                        // We're only clearing cache files, so we don't care if the
19155                        // app is unfrozen and still able to run
19156                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19157                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19158                    }
19159                    clearExternalStorageDataSync(packageName, userId, false);
19160                }
19161                if (observer != null) {
19162                    try {
19163                        observer.onRemoveCompleted(packageName, true);
19164                    } catch (RemoteException e) {
19165                        Log.i(TAG, "Observer no longer exists.");
19166                    }
19167                }
19168            }
19169        });
19170    }
19171
19172    @Override
19173    public void getPackageSizeInfo(final String packageName, int userHandle,
19174            final IPackageStatsObserver observer) {
19175        throw new UnsupportedOperationException(
19176                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19177    }
19178
19179    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19180        final PackageSetting ps;
19181        synchronized (mPackages) {
19182            ps = mSettings.mPackages.get(packageName);
19183            if (ps == null) {
19184                Slog.w(TAG, "Failed to find settings for " + packageName);
19185                return false;
19186            }
19187        }
19188
19189        final String[] packageNames = { packageName };
19190        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19191        final String[] codePaths = { ps.codePathString };
19192
19193        try {
19194            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19195                    ps.appId, ceDataInodes, codePaths, stats);
19196
19197            // For now, ignore code size of packages on system partition
19198            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19199                stats.codeSize = 0;
19200            }
19201
19202            // External clients expect these to be tracked separately
19203            stats.dataSize -= stats.cacheSize;
19204
19205        } catch (InstallerException e) {
19206            Slog.w(TAG, String.valueOf(e));
19207            return false;
19208        }
19209
19210        return true;
19211    }
19212
19213    private int getUidTargetSdkVersionLockedLPr(int uid) {
19214        Object obj = mSettings.getUserIdLPr(uid);
19215        if (obj instanceof SharedUserSetting) {
19216            final SharedUserSetting sus = (SharedUserSetting) obj;
19217            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19218            final Iterator<PackageSetting> it = sus.packages.iterator();
19219            while (it.hasNext()) {
19220                final PackageSetting ps = it.next();
19221                if (ps.pkg != null) {
19222                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19223                    if (v < vers) vers = v;
19224                }
19225            }
19226            return vers;
19227        } else if (obj instanceof PackageSetting) {
19228            final PackageSetting ps = (PackageSetting) obj;
19229            if (ps.pkg != null) {
19230                return ps.pkg.applicationInfo.targetSdkVersion;
19231            }
19232        }
19233        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19234    }
19235
19236    private int getPackageTargetSdkVersionLockedLPr(String packageName) {
19237        final PackageParser.Package p = mPackages.get(packageName);
19238        if (p != null) {
19239            return p.applicationInfo.targetSdkVersion;
19240        }
19241        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19242    }
19243
19244    @Override
19245    public void addPreferredActivity(IntentFilter filter, int match,
19246            ComponentName[] set, ComponentName activity, int userId) {
19247        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19248                "Adding preferred");
19249    }
19250
19251    private void addPreferredActivityInternal(IntentFilter filter, int match,
19252            ComponentName[] set, ComponentName activity, boolean always, int userId,
19253            String opname) {
19254        // writer
19255        int callingUid = Binder.getCallingUid();
19256        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19257                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19258        if (filter.countActions() == 0) {
19259            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19260            return;
19261        }
19262        synchronized (mPackages) {
19263            if (mContext.checkCallingOrSelfPermission(
19264                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19265                    != PackageManager.PERMISSION_GRANTED) {
19266                if (getUidTargetSdkVersionLockedLPr(callingUid)
19267                        < Build.VERSION_CODES.FROYO) {
19268                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19269                            + callingUid);
19270                    return;
19271                }
19272                mContext.enforceCallingOrSelfPermission(
19273                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19274            }
19275
19276            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19277            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19278                    + userId + ":");
19279            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19280            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19281            scheduleWritePackageRestrictionsLocked(userId);
19282            postPreferredActivityChangedBroadcast(userId);
19283        }
19284    }
19285
19286    private void postPreferredActivityChangedBroadcast(int userId) {
19287        mHandler.post(() -> {
19288            final IActivityManager am = ActivityManager.getService();
19289            if (am == null) {
19290                return;
19291            }
19292
19293            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19294            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19295            try {
19296                am.broadcastIntent(null, intent, null, null,
19297                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19298                        null, false, false, userId);
19299            } catch (RemoteException e) {
19300            }
19301        });
19302    }
19303
19304    @Override
19305    public void replacePreferredActivity(IntentFilter filter, int match,
19306            ComponentName[] set, ComponentName activity, int userId) {
19307        if (filter.countActions() != 1) {
19308            throw new IllegalArgumentException(
19309                    "replacePreferredActivity expects filter to have only 1 action.");
19310        }
19311        if (filter.countDataAuthorities() != 0
19312                || filter.countDataPaths() != 0
19313                || filter.countDataSchemes() > 1
19314                || filter.countDataTypes() != 0) {
19315            throw new IllegalArgumentException(
19316                    "replacePreferredActivity expects filter to have no data authorities, " +
19317                    "paths, or types; and at most one scheme.");
19318        }
19319
19320        final int callingUid = Binder.getCallingUid();
19321        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19322                true /* requireFullPermission */, false /* checkShell */,
19323                "replace preferred activity");
19324        synchronized (mPackages) {
19325            if (mContext.checkCallingOrSelfPermission(
19326                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19327                    != PackageManager.PERMISSION_GRANTED) {
19328                if (getUidTargetSdkVersionLockedLPr(callingUid)
19329                        < Build.VERSION_CODES.FROYO) {
19330                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19331                            + Binder.getCallingUid());
19332                    return;
19333                }
19334                mContext.enforceCallingOrSelfPermission(
19335                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19336            }
19337
19338            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19339            if (pir != null) {
19340                // Get all of the existing entries that exactly match this filter.
19341                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19342                if (existing != null && existing.size() == 1) {
19343                    PreferredActivity cur = existing.get(0);
19344                    if (DEBUG_PREFERRED) {
19345                        Slog.i(TAG, "Checking replace of preferred:");
19346                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19347                        if (!cur.mPref.mAlways) {
19348                            Slog.i(TAG, "  -- CUR; not mAlways!");
19349                        } else {
19350                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19351                            Slog.i(TAG, "  -- CUR: mSet="
19352                                    + Arrays.toString(cur.mPref.mSetComponents));
19353                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19354                            Slog.i(TAG, "  -- NEW: mMatch="
19355                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19356                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19357                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19358                        }
19359                    }
19360                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19361                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19362                            && cur.mPref.sameSet(set)) {
19363                        // Setting the preferred activity to what it happens to be already
19364                        if (DEBUG_PREFERRED) {
19365                            Slog.i(TAG, "Replacing with same preferred activity "
19366                                    + cur.mPref.mShortComponent + " for user "
19367                                    + userId + ":");
19368                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19369                        }
19370                        return;
19371                    }
19372                }
19373
19374                if (existing != null) {
19375                    if (DEBUG_PREFERRED) {
19376                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19377                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19378                    }
19379                    for (int i = 0; i < existing.size(); i++) {
19380                        PreferredActivity pa = existing.get(i);
19381                        if (DEBUG_PREFERRED) {
19382                            Slog.i(TAG, "Removing existing preferred activity "
19383                                    + pa.mPref.mComponent + ":");
19384                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19385                        }
19386                        pir.removeFilter(pa);
19387                    }
19388                }
19389            }
19390            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19391                    "Replacing preferred");
19392        }
19393    }
19394
19395    @Override
19396    public void clearPackagePreferredActivities(String packageName) {
19397        final int callingUid = Binder.getCallingUid();
19398        if (getInstantAppPackageName(callingUid) != null) {
19399            return;
19400        }
19401        // writer
19402        synchronized (mPackages) {
19403            PackageParser.Package pkg = mPackages.get(packageName);
19404            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19405                if (mContext.checkCallingOrSelfPermission(
19406                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19407                        != PackageManager.PERMISSION_GRANTED) {
19408                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19409                            < Build.VERSION_CODES.FROYO) {
19410                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19411                                + callingUid);
19412                        return;
19413                    }
19414                    mContext.enforceCallingOrSelfPermission(
19415                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19416                }
19417            }
19418            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19419            if (ps != null
19420                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19421                return;
19422            }
19423            int user = UserHandle.getCallingUserId();
19424            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19425                scheduleWritePackageRestrictionsLocked(user);
19426            }
19427        }
19428    }
19429
19430    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19431    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19432        ArrayList<PreferredActivity> removed = null;
19433        boolean changed = false;
19434        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19435            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19436            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19437            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19438                continue;
19439            }
19440            Iterator<PreferredActivity> it = pir.filterIterator();
19441            while (it.hasNext()) {
19442                PreferredActivity pa = it.next();
19443                // Mark entry for removal only if it matches the package name
19444                // and the entry is of type "always".
19445                if (packageName == null ||
19446                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19447                                && pa.mPref.mAlways)) {
19448                    if (removed == null) {
19449                        removed = new ArrayList<PreferredActivity>();
19450                    }
19451                    removed.add(pa);
19452                }
19453            }
19454            if (removed != null) {
19455                for (int j=0; j<removed.size(); j++) {
19456                    PreferredActivity pa = removed.get(j);
19457                    pir.removeFilter(pa);
19458                }
19459                changed = true;
19460            }
19461        }
19462        if (changed) {
19463            postPreferredActivityChangedBroadcast(userId);
19464        }
19465        return changed;
19466    }
19467
19468    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19469    private void clearIntentFilterVerificationsLPw(int userId) {
19470        final int packageCount = mPackages.size();
19471        for (int i = 0; i < packageCount; i++) {
19472            PackageParser.Package pkg = mPackages.valueAt(i);
19473            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19474        }
19475    }
19476
19477    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19478    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19479        if (userId == UserHandle.USER_ALL) {
19480            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19481                    sUserManager.getUserIds())) {
19482                for (int oneUserId : sUserManager.getUserIds()) {
19483                    scheduleWritePackageRestrictionsLocked(oneUserId);
19484                }
19485            }
19486        } else {
19487            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19488                scheduleWritePackageRestrictionsLocked(userId);
19489            }
19490        }
19491    }
19492
19493    /** Clears state for all users, and touches intent filter verification policy */
19494    void clearDefaultBrowserIfNeeded(String packageName) {
19495        for (int oneUserId : sUserManager.getUserIds()) {
19496            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19497        }
19498    }
19499
19500    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19501        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19502        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19503            if (packageName.equals(defaultBrowserPackageName)) {
19504                setDefaultBrowserPackageName(null, userId);
19505            }
19506        }
19507    }
19508
19509    @Override
19510    public void resetApplicationPreferences(int userId) {
19511        mContext.enforceCallingOrSelfPermission(
19512                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19513        final long identity = Binder.clearCallingIdentity();
19514        // writer
19515        try {
19516            synchronized (mPackages) {
19517                clearPackagePreferredActivitiesLPw(null, userId);
19518                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19519                // TODO: We have to reset the default SMS and Phone. This requires
19520                // significant refactoring to keep all default apps in the package
19521                // manager (cleaner but more work) or have the services provide
19522                // callbacks to the package manager to request a default app reset.
19523                applyFactoryDefaultBrowserLPw(userId);
19524                clearIntentFilterVerificationsLPw(userId);
19525                primeDomainVerificationsLPw(userId);
19526                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19527                scheduleWritePackageRestrictionsLocked(userId);
19528            }
19529            resetNetworkPolicies(userId);
19530        } finally {
19531            Binder.restoreCallingIdentity(identity);
19532        }
19533    }
19534
19535    @Override
19536    public int getPreferredActivities(List<IntentFilter> outFilters,
19537            List<ComponentName> outActivities, String packageName) {
19538        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19539            return 0;
19540        }
19541        int num = 0;
19542        final int userId = UserHandle.getCallingUserId();
19543        // reader
19544        synchronized (mPackages) {
19545            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19546            if (pir != null) {
19547                final Iterator<PreferredActivity> it = pir.filterIterator();
19548                while (it.hasNext()) {
19549                    final PreferredActivity pa = it.next();
19550                    if (packageName == null
19551                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19552                                    && pa.mPref.mAlways)) {
19553                        if (outFilters != null) {
19554                            outFilters.add(new IntentFilter(pa));
19555                        }
19556                        if (outActivities != null) {
19557                            outActivities.add(pa.mPref.mComponent);
19558                        }
19559                    }
19560                }
19561            }
19562        }
19563
19564        return num;
19565    }
19566
19567    @Override
19568    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19569            int userId) {
19570        int callingUid = Binder.getCallingUid();
19571        if (callingUid != Process.SYSTEM_UID) {
19572            throw new SecurityException(
19573                    "addPersistentPreferredActivity can only be run by the system");
19574        }
19575        if (filter.countActions() == 0) {
19576            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19577            return;
19578        }
19579        synchronized (mPackages) {
19580            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19581                    ":");
19582            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19583            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19584                    new PersistentPreferredActivity(filter, activity));
19585            scheduleWritePackageRestrictionsLocked(userId);
19586            postPreferredActivityChangedBroadcast(userId);
19587        }
19588    }
19589
19590    @Override
19591    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19592        int callingUid = Binder.getCallingUid();
19593        if (callingUid != Process.SYSTEM_UID) {
19594            throw new SecurityException(
19595                    "clearPackagePersistentPreferredActivities can only be run by the system");
19596        }
19597        ArrayList<PersistentPreferredActivity> removed = null;
19598        boolean changed = false;
19599        synchronized (mPackages) {
19600            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19601                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19602                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19603                        .valueAt(i);
19604                if (userId != thisUserId) {
19605                    continue;
19606                }
19607                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19608                while (it.hasNext()) {
19609                    PersistentPreferredActivity ppa = it.next();
19610                    // Mark entry for removal only if it matches the package name.
19611                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19612                        if (removed == null) {
19613                            removed = new ArrayList<PersistentPreferredActivity>();
19614                        }
19615                        removed.add(ppa);
19616                    }
19617                }
19618                if (removed != null) {
19619                    for (int j=0; j<removed.size(); j++) {
19620                        PersistentPreferredActivity ppa = removed.get(j);
19621                        ppir.removeFilter(ppa);
19622                    }
19623                    changed = true;
19624                }
19625            }
19626
19627            if (changed) {
19628                scheduleWritePackageRestrictionsLocked(userId);
19629                postPreferredActivityChangedBroadcast(userId);
19630            }
19631        }
19632    }
19633
19634    /**
19635     * Common machinery for picking apart a restored XML blob and passing
19636     * it to a caller-supplied functor to be applied to the running system.
19637     */
19638    private void restoreFromXml(XmlPullParser parser, int userId,
19639            String expectedStartTag, BlobXmlRestorer functor)
19640            throws IOException, XmlPullParserException {
19641        int type;
19642        while ((type = parser.next()) != XmlPullParser.START_TAG
19643                && type != XmlPullParser.END_DOCUMENT) {
19644        }
19645        if (type != XmlPullParser.START_TAG) {
19646            // oops didn't find a start tag?!
19647            if (DEBUG_BACKUP) {
19648                Slog.e(TAG, "Didn't find start tag during restore");
19649            }
19650            return;
19651        }
19652Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19653        // this is supposed to be TAG_PREFERRED_BACKUP
19654        if (!expectedStartTag.equals(parser.getName())) {
19655            if (DEBUG_BACKUP) {
19656                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19657            }
19658            return;
19659        }
19660
19661        // skip interfering stuff, then we're aligned with the backing implementation
19662        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19663Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19664        functor.apply(parser, userId);
19665    }
19666
19667    private interface BlobXmlRestorer {
19668        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19669    }
19670
19671    /**
19672     * Non-Binder method, support for the backup/restore mechanism: write the
19673     * full set of preferred activities in its canonical XML format.  Returns the
19674     * XML output as a byte array, or null if there is none.
19675     */
19676    @Override
19677    public byte[] getPreferredActivityBackup(int userId) {
19678        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19679            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19680        }
19681
19682        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19683        try {
19684            final XmlSerializer serializer = new FastXmlSerializer();
19685            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19686            serializer.startDocument(null, true);
19687            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19688
19689            synchronized (mPackages) {
19690                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19691            }
19692
19693            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19694            serializer.endDocument();
19695            serializer.flush();
19696        } catch (Exception e) {
19697            if (DEBUG_BACKUP) {
19698                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19699            }
19700            return null;
19701        }
19702
19703        return dataStream.toByteArray();
19704    }
19705
19706    @Override
19707    public void restorePreferredActivities(byte[] backup, int userId) {
19708        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19709            throw new SecurityException("Only the system may call restorePreferredActivities()");
19710        }
19711
19712        try {
19713            final XmlPullParser parser = Xml.newPullParser();
19714            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19715            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19716                    new BlobXmlRestorer() {
19717                        @Override
19718                        public void apply(XmlPullParser parser, int userId)
19719                                throws XmlPullParserException, IOException {
19720                            synchronized (mPackages) {
19721                                mSettings.readPreferredActivitiesLPw(parser, userId);
19722                            }
19723                        }
19724                    } );
19725        } catch (Exception e) {
19726            if (DEBUG_BACKUP) {
19727                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19728            }
19729        }
19730    }
19731
19732    /**
19733     * Non-Binder method, support for the backup/restore mechanism: write the
19734     * default browser (etc) settings in its canonical XML format.  Returns the default
19735     * browser XML representation as a byte array, or null if there is none.
19736     */
19737    @Override
19738    public byte[] getDefaultAppsBackup(int userId) {
19739        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19740            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19741        }
19742
19743        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19744        try {
19745            final XmlSerializer serializer = new FastXmlSerializer();
19746            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19747            serializer.startDocument(null, true);
19748            serializer.startTag(null, TAG_DEFAULT_APPS);
19749
19750            synchronized (mPackages) {
19751                mSettings.writeDefaultAppsLPr(serializer, userId);
19752            }
19753
19754            serializer.endTag(null, TAG_DEFAULT_APPS);
19755            serializer.endDocument();
19756            serializer.flush();
19757        } catch (Exception e) {
19758            if (DEBUG_BACKUP) {
19759                Slog.e(TAG, "Unable to write default apps for backup", e);
19760            }
19761            return null;
19762        }
19763
19764        return dataStream.toByteArray();
19765    }
19766
19767    @Override
19768    public void restoreDefaultApps(byte[] backup, int userId) {
19769        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19770            throw new SecurityException("Only the system may call restoreDefaultApps()");
19771        }
19772
19773        try {
19774            final XmlPullParser parser = Xml.newPullParser();
19775            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19776            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19777                    new BlobXmlRestorer() {
19778                        @Override
19779                        public void apply(XmlPullParser parser, int userId)
19780                                throws XmlPullParserException, IOException {
19781                            synchronized (mPackages) {
19782                                mSettings.readDefaultAppsLPw(parser, userId);
19783                            }
19784                        }
19785                    } );
19786        } catch (Exception e) {
19787            if (DEBUG_BACKUP) {
19788                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19789            }
19790        }
19791    }
19792
19793    @Override
19794    public byte[] getIntentFilterVerificationBackup(int userId) {
19795        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19796            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19797        }
19798
19799        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19800        try {
19801            final XmlSerializer serializer = new FastXmlSerializer();
19802            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19803            serializer.startDocument(null, true);
19804            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19805
19806            synchronized (mPackages) {
19807                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19808            }
19809
19810            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19811            serializer.endDocument();
19812            serializer.flush();
19813        } catch (Exception e) {
19814            if (DEBUG_BACKUP) {
19815                Slog.e(TAG, "Unable to write default apps for backup", e);
19816            }
19817            return null;
19818        }
19819
19820        return dataStream.toByteArray();
19821    }
19822
19823    @Override
19824    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19825        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19826            throw new SecurityException("Only the system may call restorePreferredActivities()");
19827        }
19828
19829        try {
19830            final XmlPullParser parser = Xml.newPullParser();
19831            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19832            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19833                    new BlobXmlRestorer() {
19834                        @Override
19835                        public void apply(XmlPullParser parser, int userId)
19836                                throws XmlPullParserException, IOException {
19837                            synchronized (mPackages) {
19838                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19839                                mSettings.writeLPr();
19840                            }
19841                        }
19842                    } );
19843        } catch (Exception e) {
19844            if (DEBUG_BACKUP) {
19845                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19846            }
19847        }
19848    }
19849
19850    @Override
19851    public byte[] getPermissionGrantBackup(int userId) {
19852        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19853            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19854        }
19855
19856        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19857        try {
19858            final XmlSerializer serializer = new FastXmlSerializer();
19859            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19860            serializer.startDocument(null, true);
19861            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19862
19863            synchronized (mPackages) {
19864                serializeRuntimePermissionGrantsLPr(serializer, userId);
19865            }
19866
19867            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19868            serializer.endDocument();
19869            serializer.flush();
19870        } catch (Exception e) {
19871            if (DEBUG_BACKUP) {
19872                Slog.e(TAG, "Unable to write default apps for backup", e);
19873            }
19874            return null;
19875        }
19876
19877        return dataStream.toByteArray();
19878    }
19879
19880    @Override
19881    public void restorePermissionGrants(byte[] backup, int userId) {
19882        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19883            throw new SecurityException("Only the system may call restorePermissionGrants()");
19884        }
19885
19886        try {
19887            final XmlPullParser parser = Xml.newPullParser();
19888            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19889            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19890                    new BlobXmlRestorer() {
19891                        @Override
19892                        public void apply(XmlPullParser parser, int userId)
19893                                throws XmlPullParserException, IOException {
19894                            synchronized (mPackages) {
19895                                processRestoredPermissionGrantsLPr(parser, userId);
19896                            }
19897                        }
19898                    } );
19899        } catch (Exception e) {
19900            if (DEBUG_BACKUP) {
19901                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19902            }
19903        }
19904    }
19905
19906    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19907            throws IOException {
19908        serializer.startTag(null, TAG_ALL_GRANTS);
19909
19910        final int N = mSettings.mPackages.size();
19911        for (int i = 0; i < N; i++) {
19912            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19913            boolean pkgGrantsKnown = false;
19914
19915            PermissionsState packagePerms = ps.getPermissionsState();
19916
19917            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19918                final int grantFlags = state.getFlags();
19919                // only look at grants that are not system/policy fixed
19920                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19921                    final boolean isGranted = state.isGranted();
19922                    // And only back up the user-twiddled state bits
19923                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19924                        final String packageName = mSettings.mPackages.keyAt(i);
19925                        if (!pkgGrantsKnown) {
19926                            serializer.startTag(null, TAG_GRANT);
19927                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19928                            pkgGrantsKnown = true;
19929                        }
19930
19931                        final boolean userSet =
19932                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19933                        final boolean userFixed =
19934                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19935                        final boolean revoke =
19936                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19937
19938                        serializer.startTag(null, TAG_PERMISSION);
19939                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19940                        if (isGranted) {
19941                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19942                        }
19943                        if (userSet) {
19944                            serializer.attribute(null, ATTR_USER_SET, "true");
19945                        }
19946                        if (userFixed) {
19947                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19948                        }
19949                        if (revoke) {
19950                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19951                        }
19952                        serializer.endTag(null, TAG_PERMISSION);
19953                    }
19954                }
19955            }
19956
19957            if (pkgGrantsKnown) {
19958                serializer.endTag(null, TAG_GRANT);
19959            }
19960        }
19961
19962        serializer.endTag(null, TAG_ALL_GRANTS);
19963    }
19964
19965    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19966            throws XmlPullParserException, IOException {
19967        String pkgName = null;
19968        int outerDepth = parser.getDepth();
19969        int type;
19970        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19971                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19972            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19973                continue;
19974            }
19975
19976            final String tagName = parser.getName();
19977            if (tagName.equals(TAG_GRANT)) {
19978                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19979                if (DEBUG_BACKUP) {
19980                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19981                }
19982            } else if (tagName.equals(TAG_PERMISSION)) {
19983
19984                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19985                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19986
19987                int newFlagSet = 0;
19988                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19989                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19990                }
19991                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19992                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19993                }
19994                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19995                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19996                }
19997                if (DEBUG_BACKUP) {
19998                    Slog.v(TAG, "  + Restoring grant:"
19999                            + " pkg=" + pkgName
20000                            + " perm=" + permName
20001                            + " granted=" + isGranted
20002                            + " bits=0x" + Integer.toHexString(newFlagSet));
20003                }
20004                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20005                if (ps != null) {
20006                    // Already installed so we apply the grant immediately
20007                    if (DEBUG_BACKUP) {
20008                        Slog.v(TAG, "        + already installed; applying");
20009                    }
20010                    PermissionsState perms = ps.getPermissionsState();
20011                    BasePermission bp =
20012                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
20013                    if (bp != null) {
20014                        if (isGranted) {
20015                            perms.grantRuntimePermission(bp, userId);
20016                        }
20017                        if (newFlagSet != 0) {
20018                            perms.updatePermissionFlags(
20019                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20020                        }
20021                    }
20022                } else {
20023                    // Need to wait for post-restore install to apply the grant
20024                    if (DEBUG_BACKUP) {
20025                        Slog.v(TAG, "        - not yet installed; saving for later");
20026                    }
20027                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20028                            isGranted, newFlagSet, userId);
20029                }
20030            } else {
20031                PackageManagerService.reportSettingsProblem(Log.WARN,
20032                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20033                XmlUtils.skipCurrentTag(parser);
20034            }
20035        }
20036
20037        scheduleWriteSettingsLocked();
20038        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20039    }
20040
20041    @Override
20042    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20043            int sourceUserId, int targetUserId, int flags) {
20044        mContext.enforceCallingOrSelfPermission(
20045                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20046        int callingUid = Binder.getCallingUid();
20047        enforceOwnerRights(ownerPackage, callingUid);
20048        PackageManagerServiceUtils.enforceShellRestriction(
20049                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20050        if (intentFilter.countActions() == 0) {
20051            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20052            return;
20053        }
20054        synchronized (mPackages) {
20055            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20056                    ownerPackage, targetUserId, flags);
20057            CrossProfileIntentResolver resolver =
20058                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20059            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20060            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20061            if (existing != null) {
20062                int size = existing.size();
20063                for (int i = 0; i < size; i++) {
20064                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20065                        return;
20066                    }
20067                }
20068            }
20069            resolver.addFilter(newFilter);
20070            scheduleWritePackageRestrictionsLocked(sourceUserId);
20071        }
20072    }
20073
20074    @Override
20075    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20076        mContext.enforceCallingOrSelfPermission(
20077                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20078        final int callingUid = Binder.getCallingUid();
20079        enforceOwnerRights(ownerPackage, callingUid);
20080        PackageManagerServiceUtils.enforceShellRestriction(
20081                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20082        synchronized (mPackages) {
20083            CrossProfileIntentResolver resolver =
20084                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20085            ArraySet<CrossProfileIntentFilter> set =
20086                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20087            for (CrossProfileIntentFilter filter : set) {
20088                if (filter.getOwnerPackage().equals(ownerPackage)) {
20089                    resolver.removeFilter(filter);
20090                }
20091            }
20092            scheduleWritePackageRestrictionsLocked(sourceUserId);
20093        }
20094    }
20095
20096    // Enforcing that callingUid is owning pkg on userId
20097    private void enforceOwnerRights(String pkg, int callingUid) {
20098        // The system owns everything.
20099        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20100            return;
20101        }
20102        final int callingUserId = UserHandle.getUserId(callingUid);
20103        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20104        if (pi == null) {
20105            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20106                    + callingUserId);
20107        }
20108        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20109            throw new SecurityException("Calling uid " + callingUid
20110                    + " does not own package " + pkg);
20111        }
20112    }
20113
20114    @Override
20115    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20116        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20117            return null;
20118        }
20119        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20120    }
20121
20122    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20123        UserManagerService ums = UserManagerService.getInstance();
20124        if (ums != null) {
20125            final UserInfo parent = ums.getProfileParent(userId);
20126            final int launcherUid = (parent != null) ? parent.id : userId;
20127            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20128            if (launcherComponent != null) {
20129                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20130                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20131                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20132                        .setPackage(launcherComponent.getPackageName());
20133                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20134            }
20135        }
20136    }
20137
20138    /**
20139     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20140     * then reports the most likely home activity or null if there are more than one.
20141     */
20142    private ComponentName getDefaultHomeActivity(int userId) {
20143        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20144        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20145        if (cn != null) {
20146            return cn;
20147        }
20148
20149        // Find the launcher with the highest priority and return that component if there are no
20150        // other home activity with the same priority.
20151        int lastPriority = Integer.MIN_VALUE;
20152        ComponentName lastComponent = null;
20153        final int size = allHomeCandidates.size();
20154        for (int i = 0; i < size; i++) {
20155            final ResolveInfo ri = allHomeCandidates.get(i);
20156            if (ri.priority > lastPriority) {
20157                lastComponent = ri.activityInfo.getComponentName();
20158                lastPriority = ri.priority;
20159            } else if (ri.priority == lastPriority) {
20160                // Two components found with same priority.
20161                lastComponent = null;
20162            }
20163        }
20164        return lastComponent;
20165    }
20166
20167    private Intent getHomeIntent() {
20168        Intent intent = new Intent(Intent.ACTION_MAIN);
20169        intent.addCategory(Intent.CATEGORY_HOME);
20170        intent.addCategory(Intent.CATEGORY_DEFAULT);
20171        return intent;
20172    }
20173
20174    private IntentFilter getHomeFilter() {
20175        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20176        filter.addCategory(Intent.CATEGORY_HOME);
20177        filter.addCategory(Intent.CATEGORY_DEFAULT);
20178        return filter;
20179    }
20180
20181    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20182            int userId) {
20183        Intent intent  = getHomeIntent();
20184        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20185                PackageManager.GET_META_DATA, userId);
20186        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20187                true, false, false, userId);
20188
20189        allHomeCandidates.clear();
20190        if (list != null) {
20191            for (ResolveInfo ri : list) {
20192                allHomeCandidates.add(ri);
20193            }
20194        }
20195        return (preferred == null || preferred.activityInfo == null)
20196                ? null
20197                : new ComponentName(preferred.activityInfo.packageName,
20198                        preferred.activityInfo.name);
20199    }
20200
20201    @Override
20202    public void setHomeActivity(ComponentName comp, int userId) {
20203        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20204            return;
20205        }
20206        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20207        getHomeActivitiesAsUser(homeActivities, userId);
20208
20209        boolean found = false;
20210
20211        final int size = homeActivities.size();
20212        final ComponentName[] set = new ComponentName[size];
20213        for (int i = 0; i < size; i++) {
20214            final ResolveInfo candidate = homeActivities.get(i);
20215            final ActivityInfo info = candidate.activityInfo;
20216            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20217            set[i] = activityName;
20218            if (!found && activityName.equals(comp)) {
20219                found = true;
20220            }
20221        }
20222        if (!found) {
20223            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20224                    + userId);
20225        }
20226        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20227                set, comp, userId);
20228    }
20229
20230    private @Nullable String getSetupWizardPackageName() {
20231        final Intent intent = new Intent(Intent.ACTION_MAIN);
20232        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20233
20234        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20235                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20236                        | MATCH_DISABLED_COMPONENTS,
20237                UserHandle.myUserId());
20238        if (matches.size() == 1) {
20239            return matches.get(0).getComponentInfo().packageName;
20240        } else {
20241            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20242                    + ": matches=" + matches);
20243            return null;
20244        }
20245    }
20246
20247    private @Nullable String getStorageManagerPackageName() {
20248        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20249
20250        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20251                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20252                        | MATCH_DISABLED_COMPONENTS,
20253                UserHandle.myUserId());
20254        if (matches.size() == 1) {
20255            return matches.get(0).getComponentInfo().packageName;
20256        } else {
20257            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20258                    + matches.size() + ": matches=" + matches);
20259            return null;
20260        }
20261    }
20262
20263    @Override
20264    public String getSystemTextClassifierPackageName() {
20265        return mContext.getString(R.string.config_defaultTextClassifierPackage);
20266    }
20267
20268    @Override
20269    public void setApplicationEnabledSetting(String appPackageName,
20270            int newState, int flags, int userId, String callingPackage) {
20271        if (!sUserManager.exists(userId)) return;
20272        if (callingPackage == null) {
20273            callingPackage = Integer.toString(Binder.getCallingUid());
20274        }
20275        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20276    }
20277
20278    @Override
20279    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20280        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20281        synchronized (mPackages) {
20282            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20283            if (pkgSetting != null) {
20284                pkgSetting.setUpdateAvailable(updateAvailable);
20285            }
20286        }
20287    }
20288
20289    @Override
20290    public void setComponentEnabledSetting(ComponentName componentName,
20291            int newState, int flags, int userId) {
20292        if (!sUserManager.exists(userId)) return;
20293        setEnabledSetting(componentName.getPackageName(),
20294                componentName.getClassName(), newState, flags, userId, null);
20295    }
20296
20297    private void setEnabledSetting(final String packageName, String className, int newState,
20298            final int flags, int userId, String callingPackage) {
20299        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20300              || newState == COMPONENT_ENABLED_STATE_ENABLED
20301              || newState == COMPONENT_ENABLED_STATE_DISABLED
20302              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20303              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20304            throw new IllegalArgumentException("Invalid new component state: "
20305                    + newState);
20306        }
20307        PackageSetting pkgSetting;
20308        final int callingUid = Binder.getCallingUid();
20309        final int permission;
20310        if (callingUid == Process.SYSTEM_UID) {
20311            permission = PackageManager.PERMISSION_GRANTED;
20312        } else {
20313            permission = mContext.checkCallingOrSelfPermission(
20314                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20315        }
20316        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20317                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20318        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20319        boolean sendNow = false;
20320        boolean isApp = (className == null);
20321        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20322        String componentName = isApp ? packageName : className;
20323        int packageUid = -1;
20324        ArrayList<String> components;
20325
20326        // reader
20327        synchronized (mPackages) {
20328            pkgSetting = mSettings.mPackages.get(packageName);
20329            if (pkgSetting == null) {
20330                if (!isCallerInstantApp) {
20331                    if (className == null) {
20332                        throw new IllegalArgumentException("Unknown package: " + packageName);
20333                    }
20334                    throw new IllegalArgumentException(
20335                            "Unknown component: " + packageName + "/" + className);
20336                } else {
20337                    // throw SecurityException to prevent leaking package information
20338                    throw new SecurityException(
20339                            "Attempt to change component state; "
20340                            + "pid=" + Binder.getCallingPid()
20341                            + ", uid=" + callingUid
20342                            + (className == null
20343                                    ? ", package=" + packageName
20344                                    : ", component=" + packageName + "/" + className));
20345                }
20346            }
20347        }
20348
20349        // Limit who can change which apps
20350        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20351            // Don't allow apps that don't have permission to modify other apps
20352            if (!allowedByPermission
20353                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20354                throw new SecurityException(
20355                        "Attempt to change component state; "
20356                        + "pid=" + Binder.getCallingPid()
20357                        + ", uid=" + callingUid
20358                        + (className == null
20359                                ? ", package=" + packageName
20360                                : ", component=" + packageName + "/" + className));
20361            }
20362            // Don't allow changing protected packages.
20363            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20364                throw new SecurityException("Cannot disable a protected package: " + packageName);
20365            }
20366        }
20367
20368        synchronized (mPackages) {
20369            if (callingUid == Process.SHELL_UID
20370                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20371                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20372                // unless it is a test package.
20373                int oldState = pkgSetting.getEnabled(userId);
20374                if (className == null
20375                        &&
20376                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20377                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20378                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20379                        &&
20380                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20381                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20382                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20383                    // ok
20384                } else {
20385                    throw new SecurityException(
20386                            "Shell cannot change component state for " + packageName + "/"
20387                                    + className + " to " + newState);
20388                }
20389            }
20390        }
20391        if (className == null) {
20392            // We're dealing with an application/package level state change
20393            synchronized (mPackages) {
20394                if (pkgSetting.getEnabled(userId) == newState) {
20395                    // Nothing to do
20396                    return;
20397                }
20398            }
20399            // If we're enabling a system stub, there's a little more work to do.
20400            // Prior to enabling the package, we need to decompress the APK(s) to the
20401            // data partition and then replace the version on the system partition.
20402            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20403            final boolean isSystemStub = deletedPkg.isStub
20404                    && deletedPkg.isSystem();
20405            if (isSystemStub
20406                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20407                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20408                final File codePath = decompressPackage(deletedPkg);
20409                if (codePath == null) {
20410                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20411                    return;
20412                }
20413                // TODO remove direct parsing of the package object during internal cleanup
20414                // of scan package
20415                // We need to call parse directly here for no other reason than we need
20416                // the new package in order to disable the old one [we use the information
20417                // for some internal optimization to optionally create a new package setting
20418                // object on replace]. However, we can't get the package from the scan
20419                // because the scan modifies live structures and we need to remove the
20420                // old [system] package from the system before a scan can be attempted.
20421                // Once scan is indempotent we can remove this parse and use the package
20422                // object we scanned, prior to adding it to package settings.
20423                final PackageParser pp = new PackageParser();
20424                pp.setSeparateProcesses(mSeparateProcesses);
20425                pp.setDisplayMetrics(mMetrics);
20426                pp.setCallback(mPackageParserCallback);
20427                final PackageParser.Package tmpPkg;
20428                try {
20429                    final @ParseFlags int parseFlags = mDefParseFlags
20430                            | PackageParser.PARSE_MUST_BE_APK
20431                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20432                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20433                } catch (PackageParserException e) {
20434                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20435                    return;
20436                }
20437                synchronized (mInstallLock) {
20438                    // Disable the stub and remove any package entries
20439                    removePackageLI(deletedPkg, true);
20440                    synchronized (mPackages) {
20441                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20442                    }
20443                    final PackageParser.Package pkg;
20444                    try (PackageFreezer freezer =
20445                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20446                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20447                                | PackageParser.PARSE_ENFORCE_CODE;
20448                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20449                                0 /*currentTime*/, null /*user*/);
20450                        prepareAppDataAfterInstallLIF(pkg);
20451                        synchronized (mPackages) {
20452                            try {
20453                                updateSharedLibrariesLPr(pkg, null);
20454                            } catch (PackageManagerException e) {
20455                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20456                            }
20457                            mPermissionManager.updatePermissions(
20458                                    pkg.packageName, pkg, true, mPackages.values(),
20459                                    mPermissionCallback);
20460                            mSettings.writeLPr();
20461                        }
20462                    } catch (PackageManagerException e) {
20463                        // Whoops! Something went wrong; try to roll back to the stub
20464                        Slog.w(TAG, "Failed to install compressed system package:"
20465                                + pkgSetting.name, e);
20466                        // Remove the failed install
20467                        removeCodePathLI(codePath);
20468
20469                        // Install the system package
20470                        try (PackageFreezer freezer =
20471                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20472                            synchronized (mPackages) {
20473                                // NOTE: The system package always needs to be enabled; even
20474                                // if it's for a compressed stub. If we don't, installing the
20475                                // system package fails during scan [scanning checks the disabled
20476                                // packages]. We will reverse this later, after we've "installed"
20477                                // the stub.
20478                                // This leaves us in a fragile state; the stub should never be
20479                                // enabled, so, cross your fingers and hope nothing goes wrong
20480                                // until we can disable the package later.
20481                                enableSystemPackageLPw(deletedPkg);
20482                            }
20483                            installPackageFromSystemLIF(deletedPkg.codePath,
20484                                    false /*isPrivileged*/, null /*allUserHandles*/,
20485                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20486                                    true /*writeSettings*/);
20487                        } catch (PackageManagerException pme) {
20488                            Slog.w(TAG, "Failed to restore system package:"
20489                                    + deletedPkg.packageName, pme);
20490                        } finally {
20491                            synchronized (mPackages) {
20492                                mSettings.disableSystemPackageLPw(
20493                                        deletedPkg.packageName, true /*replaced*/);
20494                                mSettings.writeLPr();
20495                            }
20496                        }
20497                        return;
20498                    }
20499                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20500                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20501                    mDexManager.notifyPackageUpdated(pkg.packageName,
20502                            pkg.baseCodePath, pkg.splitCodePaths);
20503                }
20504            }
20505            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20506                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20507                // Don't care about who enables an app.
20508                callingPackage = null;
20509            }
20510            synchronized (mPackages) {
20511                pkgSetting.setEnabled(newState, userId, callingPackage);
20512            }
20513        } else {
20514            synchronized (mPackages) {
20515                // We're dealing with a component level state change
20516                // First, verify that this is a valid class name.
20517                PackageParser.Package pkg = pkgSetting.pkg;
20518                if (pkg == null || !pkg.hasComponentClassName(className)) {
20519                    if (pkg != null &&
20520                            pkg.applicationInfo.targetSdkVersion >=
20521                                    Build.VERSION_CODES.JELLY_BEAN) {
20522                        throw new IllegalArgumentException("Component class " + className
20523                                + " does not exist in " + packageName);
20524                    } else {
20525                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20526                                + className + " does not exist in " + packageName);
20527                    }
20528                }
20529                switch (newState) {
20530                    case COMPONENT_ENABLED_STATE_ENABLED:
20531                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20532                            return;
20533                        }
20534                        break;
20535                    case COMPONENT_ENABLED_STATE_DISABLED:
20536                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20537                            return;
20538                        }
20539                        break;
20540                    case COMPONENT_ENABLED_STATE_DEFAULT:
20541                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20542                            return;
20543                        }
20544                        break;
20545                    default:
20546                        Slog.e(TAG, "Invalid new component state: " + newState);
20547                        return;
20548                }
20549            }
20550        }
20551        synchronized (mPackages) {
20552            scheduleWritePackageRestrictionsLocked(userId);
20553            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20554            final long callingId = Binder.clearCallingIdentity();
20555            try {
20556                updateInstantAppInstallerLocked(packageName);
20557            } finally {
20558                Binder.restoreCallingIdentity(callingId);
20559            }
20560            components = mPendingBroadcasts.get(userId, packageName);
20561            final boolean newPackage = components == null;
20562            if (newPackage) {
20563                components = new ArrayList<String>();
20564            }
20565            if (!components.contains(componentName)) {
20566                components.add(componentName);
20567            }
20568            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20569                sendNow = true;
20570                // Purge entry from pending broadcast list if another one exists already
20571                // since we are sending one right away.
20572                mPendingBroadcasts.remove(userId, packageName);
20573            } else {
20574                if (newPackage) {
20575                    mPendingBroadcasts.put(userId, packageName, components);
20576                }
20577                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20578                    // Schedule a message
20579                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20580                }
20581            }
20582        }
20583
20584        long callingId = Binder.clearCallingIdentity();
20585        try {
20586            if (sendNow) {
20587                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20588                sendPackageChangedBroadcast(packageName,
20589                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20590            }
20591        } finally {
20592            Binder.restoreCallingIdentity(callingId);
20593        }
20594    }
20595
20596    @Override
20597    public void flushPackageRestrictionsAsUser(int userId) {
20598        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20599            return;
20600        }
20601        if (!sUserManager.exists(userId)) {
20602            return;
20603        }
20604        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20605                false /* checkShell */, "flushPackageRestrictions");
20606        synchronized (mPackages) {
20607            mSettings.writePackageRestrictionsLPr(userId);
20608            mDirtyUsers.remove(userId);
20609            if (mDirtyUsers.isEmpty()) {
20610                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20611            }
20612        }
20613    }
20614
20615    private void sendPackageChangedBroadcast(String packageName,
20616            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20617        if (DEBUG_INSTALL)
20618            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20619                    + componentNames);
20620        Bundle extras = new Bundle(4);
20621        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20622        String nameList[] = new String[componentNames.size()];
20623        componentNames.toArray(nameList);
20624        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20625        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20626        extras.putInt(Intent.EXTRA_UID, packageUid);
20627        // If this is not reporting a change of the overall package, then only send it
20628        // to registered receivers.  We don't want to launch a swath of apps for every
20629        // little component state change.
20630        final int flags = !componentNames.contains(packageName)
20631                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20632        final int userId = UserHandle.getUserId(packageUid);
20633        final boolean isInstantApp = isInstantApp(packageName, userId);
20634        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20635        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20636        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20637                userIds, instantUserIds);
20638    }
20639
20640    @Override
20641    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20642        if (!sUserManager.exists(userId)) return;
20643        final int callingUid = Binder.getCallingUid();
20644        if (getInstantAppPackageName(callingUid) != null) {
20645            return;
20646        }
20647        final int permission = mContext.checkCallingOrSelfPermission(
20648                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20649        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20650        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20651                true /* requireFullPermission */, true /* checkShell */, "stop package");
20652        // writer
20653        synchronized (mPackages) {
20654            final PackageSetting ps = mSettings.mPackages.get(packageName);
20655            if (!filterAppAccessLPr(ps, callingUid, userId)
20656                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20657                            allowedByPermission, callingUid, userId)) {
20658                scheduleWritePackageRestrictionsLocked(userId);
20659            }
20660        }
20661    }
20662
20663    @Override
20664    public String getInstallerPackageName(String packageName) {
20665        final int callingUid = Binder.getCallingUid();
20666        synchronized (mPackages) {
20667            final PackageSetting ps = mSettings.mPackages.get(packageName);
20668            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20669                return null;
20670            }
20671            return mSettings.getInstallerPackageNameLPr(packageName);
20672        }
20673    }
20674
20675    public boolean isOrphaned(String packageName) {
20676        // reader
20677        synchronized (mPackages) {
20678            return mSettings.isOrphaned(packageName);
20679        }
20680    }
20681
20682    @Override
20683    public int getApplicationEnabledSetting(String packageName, int userId) {
20684        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20685        int callingUid = Binder.getCallingUid();
20686        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20687                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20688        // reader
20689        synchronized (mPackages) {
20690            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20691                return COMPONENT_ENABLED_STATE_DISABLED;
20692            }
20693            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20694        }
20695    }
20696
20697    @Override
20698    public int getComponentEnabledSetting(ComponentName component, int userId) {
20699        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20700        int callingUid = Binder.getCallingUid();
20701        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20702                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20703        synchronized (mPackages) {
20704            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20705                    component, TYPE_UNKNOWN, userId)) {
20706                return COMPONENT_ENABLED_STATE_DISABLED;
20707            }
20708            return mSettings.getComponentEnabledSettingLPr(component, userId);
20709        }
20710    }
20711
20712    @Override
20713    public void enterSafeMode() {
20714        enforceSystemOrRoot("Only the system can request entering safe mode");
20715
20716        if (!mSystemReady) {
20717            mSafeMode = true;
20718        }
20719    }
20720
20721    @Override
20722    public void systemReady() {
20723        enforceSystemOrRoot("Only the system can claim the system is ready");
20724
20725        mSystemReady = true;
20726        final ContentResolver resolver = mContext.getContentResolver();
20727        ContentObserver co = new ContentObserver(mHandler) {
20728            @Override
20729            public void onChange(boolean selfChange) {
20730                mWebInstantAppsDisabled =
20731                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20732                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20733            }
20734        };
20735        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20736                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20737                false, co, UserHandle.USER_SYSTEM);
20738        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure
20739                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20740        co.onChange(true);
20741
20742        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20743        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20744        // it is done.
20745        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20746            @Override
20747            public void onChange(boolean selfChange) {
20748                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20749                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20750                        oobEnabled == 1 ? "true" : "false");
20751            }
20752        };
20753        mContext.getContentResolver().registerContentObserver(
20754                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20755                UserHandle.USER_SYSTEM);
20756        // At boot, restore the value from the setting, which persists across reboot.
20757        privAppOobObserver.onChange(true);
20758
20759        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20760        // disabled after already being started.
20761        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20762                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20763
20764        // Read the compatibilty setting when the system is ready.
20765        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20766                mContext.getContentResolver(),
20767                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20768        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20769        if (DEBUG_SETTINGS) {
20770            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20771        }
20772
20773        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20774
20775        synchronized (mPackages) {
20776            // Verify that all of the preferred activity components actually
20777            // exist.  It is possible for applications to be updated and at
20778            // that point remove a previously declared activity component that
20779            // had been set as a preferred activity.  We try to clean this up
20780            // the next time we encounter that preferred activity, but it is
20781            // possible for the user flow to never be able to return to that
20782            // situation so here we do a sanity check to make sure we haven't
20783            // left any junk around.
20784            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20785            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20786                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20787                removed.clear();
20788                for (PreferredActivity pa : pir.filterSet()) {
20789                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20790                        removed.add(pa);
20791                    }
20792                }
20793                if (removed.size() > 0) {
20794                    for (int r=0; r<removed.size(); r++) {
20795                        PreferredActivity pa = removed.get(r);
20796                        Slog.w(TAG, "Removing dangling preferred activity: "
20797                                + pa.mPref.mComponent);
20798                        pir.removeFilter(pa);
20799                    }
20800                    mSettings.writePackageRestrictionsLPr(
20801                            mSettings.mPreferredActivities.keyAt(i));
20802                }
20803            }
20804
20805            for (int userId : UserManagerService.getInstance().getUserIds()) {
20806                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20807                    grantPermissionsUserIds = ArrayUtils.appendInt(
20808                            grantPermissionsUserIds, userId);
20809                }
20810            }
20811        }
20812        sUserManager.systemReady();
20813        // If we upgraded grant all default permissions before kicking off.
20814        for (int userId : grantPermissionsUserIds) {
20815            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20816        }
20817
20818        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20819            // If we did not grant default permissions, we preload from this the
20820            // default permission exceptions lazily to ensure we don't hit the
20821            // disk on a new user creation.
20822            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20823        }
20824
20825        // Now that we've scanned all packages, and granted any default
20826        // permissions, ensure permissions are updated. Beware of dragons if you
20827        // try optimizing this.
20828        synchronized (mPackages) {
20829            mPermissionManager.updateAllPermissions(
20830                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
20831                    mPermissionCallback);
20832        }
20833
20834        // Kick off any messages waiting for system ready
20835        if (mPostSystemReadyMessages != null) {
20836            for (Message msg : mPostSystemReadyMessages) {
20837                msg.sendToTarget();
20838            }
20839            mPostSystemReadyMessages = null;
20840        }
20841
20842        // Watch for external volumes that come and go over time
20843        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20844        storage.registerListener(mStorageListener);
20845
20846        mInstallerService.systemReady();
20847        mPackageDexOptimizer.systemReady();
20848
20849        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20850                StorageManagerInternal.class);
20851        StorageManagerInternal.addExternalStoragePolicy(
20852                new StorageManagerInternal.ExternalStorageMountPolicy() {
20853            @Override
20854            public int getMountMode(int uid, String packageName) {
20855                if (Process.isIsolated(uid)) {
20856                    return Zygote.MOUNT_EXTERNAL_NONE;
20857                }
20858                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20859                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20860                }
20861                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20862                    return Zygote.MOUNT_EXTERNAL_READ;
20863                }
20864                return Zygote.MOUNT_EXTERNAL_WRITE;
20865            }
20866
20867            @Override
20868            public boolean hasExternalStorage(int uid, String packageName) {
20869                return true;
20870            }
20871        });
20872
20873        // Now that we're mostly running, clean up stale users and apps
20874        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20875        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20876
20877        mPermissionManager.systemReady();
20878
20879        if (mInstantAppResolverConnection != null) {
20880            mContext.registerReceiver(new BroadcastReceiver() {
20881                @Override
20882                public void onReceive(Context context, Intent intent) {
20883                    mInstantAppResolverConnection.optimisticBind();
20884                    mContext.unregisterReceiver(this);
20885                }
20886            }, new IntentFilter(Intent.ACTION_BOOT_COMPLETED));
20887        }
20888    }
20889
20890    public void waitForAppDataPrepared() {
20891        if (mPrepareAppDataFuture == null) {
20892            return;
20893        }
20894        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20895        mPrepareAppDataFuture = null;
20896    }
20897
20898    @Override
20899    public boolean isSafeMode() {
20900        // allow instant applications
20901        return mSafeMode;
20902    }
20903
20904    @Override
20905    public boolean hasSystemUidErrors() {
20906        // allow instant applications
20907        return mHasSystemUidErrors;
20908    }
20909
20910    static String arrayToString(int[] array) {
20911        StringBuffer buf = new StringBuffer(128);
20912        buf.append('[');
20913        if (array != null) {
20914            for (int i=0; i<array.length; i++) {
20915                if (i > 0) buf.append(", ");
20916                buf.append(array[i]);
20917            }
20918        }
20919        buf.append(']');
20920        return buf.toString();
20921    }
20922
20923    @Override
20924    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20925            FileDescriptor err, String[] args, ShellCallback callback,
20926            ResultReceiver resultReceiver) {
20927        (new PackageManagerShellCommand(this)).exec(
20928                this, in, out, err, args, callback, resultReceiver);
20929    }
20930
20931    @Override
20932    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20933        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20934
20935        DumpState dumpState = new DumpState();
20936        boolean fullPreferred = false;
20937        boolean checkin = false;
20938
20939        String packageName = null;
20940        ArraySet<String> permissionNames = null;
20941
20942        int opti = 0;
20943        while (opti < args.length) {
20944            String opt = args[opti];
20945            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20946                break;
20947            }
20948            opti++;
20949
20950            if ("-a".equals(opt)) {
20951                // Right now we only know how to print all.
20952            } else if ("-h".equals(opt)) {
20953                pw.println("Package manager dump options:");
20954                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20955                pw.println("    --checkin: dump for a checkin");
20956                pw.println("    -f: print details of intent filters");
20957                pw.println("    -h: print this help");
20958                pw.println("  cmd may be one of:");
20959                pw.println("    l[ibraries]: list known shared libraries");
20960                pw.println("    f[eatures]: list device features");
20961                pw.println("    k[eysets]: print known keysets");
20962                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20963                pw.println("    perm[issions]: dump permissions");
20964                pw.println("    permission [name ...]: dump declaration and use of given permission");
20965                pw.println("    pref[erred]: print preferred package settings");
20966                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20967                pw.println("    prov[iders]: dump content providers");
20968                pw.println("    p[ackages]: dump installed packages");
20969                pw.println("    s[hared-users]: dump shared user IDs");
20970                pw.println("    m[essages]: print collected runtime messages");
20971                pw.println("    v[erifiers]: print package verifier info");
20972                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20973                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20974                pw.println("    version: print database version info");
20975                pw.println("    write: write current settings now");
20976                pw.println("    installs: details about install sessions");
20977                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20978                pw.println("    dexopt: dump dexopt state");
20979                pw.println("    compiler-stats: dump compiler statistics");
20980                pw.println("    service-permissions: dump permissions required by services");
20981                pw.println("    <package.name>: info about given package");
20982                return;
20983            } else if ("--checkin".equals(opt)) {
20984                checkin = true;
20985            } else if ("-f".equals(opt)) {
20986                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20987            } else if ("--proto".equals(opt)) {
20988                dumpProto(fd);
20989                return;
20990            } else {
20991                pw.println("Unknown argument: " + opt + "; use -h for help");
20992            }
20993        }
20994
20995        // Is the caller requesting to dump a particular piece of data?
20996        if (opti < args.length) {
20997            String cmd = args[opti];
20998            opti++;
20999            // Is this a package name?
21000            if ("android".equals(cmd) || cmd.contains(".")) {
21001                packageName = cmd;
21002                // When dumping a single package, we always dump all of its
21003                // filter information since the amount of data will be reasonable.
21004                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21005            } else if ("check-permission".equals(cmd)) {
21006                if (opti >= args.length) {
21007                    pw.println("Error: check-permission missing permission argument");
21008                    return;
21009                }
21010                String perm = args[opti];
21011                opti++;
21012                if (opti >= args.length) {
21013                    pw.println("Error: check-permission missing package argument");
21014                    return;
21015                }
21016
21017                String pkg = args[opti];
21018                opti++;
21019                int user = UserHandle.getUserId(Binder.getCallingUid());
21020                if (opti < args.length) {
21021                    try {
21022                        user = Integer.parseInt(args[opti]);
21023                    } catch (NumberFormatException e) {
21024                        pw.println("Error: check-permission user argument is not a number: "
21025                                + args[opti]);
21026                        return;
21027                    }
21028                }
21029
21030                // Normalize package name to handle renamed packages and static libs
21031                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21032
21033                pw.println(checkPermission(perm, pkg, user));
21034                return;
21035            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21036                dumpState.setDump(DumpState.DUMP_LIBS);
21037            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21038                dumpState.setDump(DumpState.DUMP_FEATURES);
21039            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21040                if (opti >= args.length) {
21041                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21042                            | DumpState.DUMP_SERVICE_RESOLVERS
21043                            | DumpState.DUMP_RECEIVER_RESOLVERS
21044                            | DumpState.DUMP_CONTENT_RESOLVERS);
21045                } else {
21046                    while (opti < args.length) {
21047                        String name = args[opti];
21048                        if ("a".equals(name) || "activity".equals(name)) {
21049                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21050                        } else if ("s".equals(name) || "service".equals(name)) {
21051                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21052                        } else if ("r".equals(name) || "receiver".equals(name)) {
21053                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21054                        } else if ("c".equals(name) || "content".equals(name)) {
21055                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21056                        } else {
21057                            pw.println("Error: unknown resolver table type: " + name);
21058                            return;
21059                        }
21060                        opti++;
21061                    }
21062                }
21063            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21064                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21065            } else if ("permission".equals(cmd)) {
21066                if (opti >= args.length) {
21067                    pw.println("Error: permission requires permission name");
21068                    return;
21069                }
21070                permissionNames = new ArraySet<>();
21071                while (opti < args.length) {
21072                    permissionNames.add(args[opti]);
21073                    opti++;
21074                }
21075                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21076                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21077            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21078                dumpState.setDump(DumpState.DUMP_PREFERRED);
21079            } else if ("preferred-xml".equals(cmd)) {
21080                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21081                if (opti < args.length && "--full".equals(args[opti])) {
21082                    fullPreferred = true;
21083                    opti++;
21084                }
21085            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21086                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21087            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21088                dumpState.setDump(DumpState.DUMP_PACKAGES);
21089            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21090                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21091            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21092                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21093            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21094                dumpState.setDump(DumpState.DUMP_MESSAGES);
21095            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21096                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21097            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21098                    || "intent-filter-verifiers".equals(cmd)) {
21099                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21100            } else if ("version".equals(cmd)) {
21101                dumpState.setDump(DumpState.DUMP_VERSION);
21102            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21103                dumpState.setDump(DumpState.DUMP_KEYSETS);
21104            } else if ("installs".equals(cmd)) {
21105                dumpState.setDump(DumpState.DUMP_INSTALLS);
21106            } else if ("frozen".equals(cmd)) {
21107                dumpState.setDump(DumpState.DUMP_FROZEN);
21108            } else if ("volumes".equals(cmd)) {
21109                dumpState.setDump(DumpState.DUMP_VOLUMES);
21110            } else if ("dexopt".equals(cmd)) {
21111                dumpState.setDump(DumpState.DUMP_DEXOPT);
21112            } else if ("compiler-stats".equals(cmd)) {
21113                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21114            } else if ("changes".equals(cmd)) {
21115                dumpState.setDump(DumpState.DUMP_CHANGES);
21116            } else if ("service-permissions".equals(cmd)) {
21117                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
21118            } else if ("write".equals(cmd)) {
21119                synchronized (mPackages) {
21120                    mSettings.writeLPr();
21121                    pw.println("Settings written.");
21122                    return;
21123                }
21124            }
21125        }
21126
21127        if (checkin) {
21128            pw.println("vers,1");
21129        }
21130
21131        // reader
21132        synchronized (mPackages) {
21133            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21134                if (!checkin) {
21135                    if (dumpState.onTitlePrinted())
21136                        pw.println();
21137                    pw.println("Database versions:");
21138                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21139                }
21140            }
21141
21142            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21143                if (!checkin) {
21144                    if (dumpState.onTitlePrinted())
21145                        pw.println();
21146                    pw.println("Verifiers:");
21147                    pw.print("  Required: ");
21148                    pw.print(mRequiredVerifierPackage);
21149                    pw.print(" (uid=");
21150                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21151                            UserHandle.USER_SYSTEM));
21152                    pw.println(")");
21153                } else if (mRequiredVerifierPackage != null) {
21154                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21155                    pw.print(",");
21156                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21157                            UserHandle.USER_SYSTEM));
21158                }
21159            }
21160
21161            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21162                    packageName == null) {
21163                if (mIntentFilterVerifierComponent != null) {
21164                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21165                    if (!checkin) {
21166                        if (dumpState.onTitlePrinted())
21167                            pw.println();
21168                        pw.println("Intent Filter Verifier:");
21169                        pw.print("  Using: ");
21170                        pw.print(verifierPackageName);
21171                        pw.print(" (uid=");
21172                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21173                                UserHandle.USER_SYSTEM));
21174                        pw.println(")");
21175                    } else if (verifierPackageName != null) {
21176                        pw.print("ifv,"); pw.print(verifierPackageName);
21177                        pw.print(",");
21178                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21179                                UserHandle.USER_SYSTEM));
21180                    }
21181                } else {
21182                    pw.println();
21183                    pw.println("No Intent Filter Verifier available!");
21184                }
21185            }
21186
21187            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21188                boolean printedHeader = false;
21189                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21190                while (it.hasNext()) {
21191                    String libName = it.next();
21192                    LongSparseArray<SharedLibraryEntry> versionedLib
21193                            = mSharedLibraries.get(libName);
21194                    if (versionedLib == null) {
21195                        continue;
21196                    }
21197                    final int versionCount = versionedLib.size();
21198                    for (int i = 0; i < versionCount; i++) {
21199                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21200                        if (!checkin) {
21201                            if (!printedHeader) {
21202                                if (dumpState.onTitlePrinted())
21203                                    pw.println();
21204                                pw.println("Libraries:");
21205                                printedHeader = true;
21206                            }
21207                            pw.print("  ");
21208                        } else {
21209                            pw.print("lib,");
21210                        }
21211                        pw.print(libEntry.info.getName());
21212                        if (libEntry.info.isStatic()) {
21213                            pw.print(" version=" + libEntry.info.getLongVersion());
21214                        }
21215                        if (!checkin) {
21216                            pw.print(" -> ");
21217                        }
21218                        if (libEntry.path != null) {
21219                            pw.print(" (jar) ");
21220                            pw.print(libEntry.path);
21221                        } else {
21222                            pw.print(" (apk) ");
21223                            pw.print(libEntry.apk);
21224                        }
21225                        pw.println();
21226                    }
21227                }
21228            }
21229
21230            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21231                if (dumpState.onTitlePrinted())
21232                    pw.println();
21233                if (!checkin) {
21234                    pw.println("Features:");
21235                }
21236
21237                synchronized (mAvailableFeatures) {
21238                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21239                        if (checkin) {
21240                            pw.print("feat,");
21241                            pw.print(feat.name);
21242                            pw.print(",");
21243                            pw.println(feat.version);
21244                        } else {
21245                            pw.print("  ");
21246                            pw.print(feat.name);
21247                            if (feat.version > 0) {
21248                                pw.print(" version=");
21249                                pw.print(feat.version);
21250                            }
21251                            pw.println();
21252                        }
21253                    }
21254                }
21255            }
21256
21257            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21258                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21259                        : "Activity Resolver Table:", "  ", packageName,
21260                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21261                    dumpState.setTitlePrinted(true);
21262                }
21263            }
21264            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21265                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21266                        : "Receiver Resolver Table:", "  ", packageName,
21267                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21268                    dumpState.setTitlePrinted(true);
21269                }
21270            }
21271            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21272                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21273                        : "Service Resolver Table:", "  ", packageName,
21274                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21275                    dumpState.setTitlePrinted(true);
21276                }
21277            }
21278            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21279                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21280                        : "Provider Resolver Table:", "  ", packageName,
21281                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21282                    dumpState.setTitlePrinted(true);
21283                }
21284            }
21285
21286            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21287                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21288                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21289                    int user = mSettings.mPreferredActivities.keyAt(i);
21290                    if (pir.dump(pw,
21291                            dumpState.getTitlePrinted()
21292                                ? "\nPreferred Activities User " + user + ":"
21293                                : "Preferred Activities User " + user + ":", "  ",
21294                            packageName, true, false)) {
21295                        dumpState.setTitlePrinted(true);
21296                    }
21297                }
21298            }
21299
21300            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21301                pw.flush();
21302                FileOutputStream fout = new FileOutputStream(fd);
21303                BufferedOutputStream str = new BufferedOutputStream(fout);
21304                XmlSerializer serializer = new FastXmlSerializer();
21305                try {
21306                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21307                    serializer.startDocument(null, true);
21308                    serializer.setFeature(
21309                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21310                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21311                    serializer.endDocument();
21312                    serializer.flush();
21313                } catch (IllegalArgumentException e) {
21314                    pw.println("Failed writing: " + e);
21315                } catch (IllegalStateException e) {
21316                    pw.println("Failed writing: " + e);
21317                } catch (IOException e) {
21318                    pw.println("Failed writing: " + e);
21319                }
21320            }
21321
21322            if (!checkin
21323                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21324                    && packageName == null) {
21325                pw.println();
21326                int count = mSettings.mPackages.size();
21327                if (count == 0) {
21328                    pw.println("No applications!");
21329                    pw.println();
21330                } else {
21331                    final String prefix = "  ";
21332                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21333                    if (allPackageSettings.size() == 0) {
21334                        pw.println("No domain preferred apps!");
21335                        pw.println();
21336                    } else {
21337                        pw.println("App verification status:");
21338                        pw.println();
21339                        count = 0;
21340                        for (PackageSetting ps : allPackageSettings) {
21341                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21342                            if (ivi == null || ivi.getPackageName() == null) continue;
21343                            pw.println(prefix + "Package: " + ivi.getPackageName());
21344                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21345                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21346                            pw.println();
21347                            count++;
21348                        }
21349                        if (count == 0) {
21350                            pw.println(prefix + "No app verification established.");
21351                            pw.println();
21352                        }
21353                        for (int userId : sUserManager.getUserIds()) {
21354                            pw.println("App linkages for user " + userId + ":");
21355                            pw.println();
21356                            count = 0;
21357                            for (PackageSetting ps : allPackageSettings) {
21358                                final long status = ps.getDomainVerificationStatusForUser(userId);
21359                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21360                                        && !DEBUG_DOMAIN_VERIFICATION) {
21361                                    continue;
21362                                }
21363                                pw.println(prefix + "Package: " + ps.name);
21364                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21365                                String statusStr = IntentFilterVerificationInfo.
21366                                        getStatusStringFromValue(status);
21367                                pw.println(prefix + "Status:  " + statusStr);
21368                                pw.println();
21369                                count++;
21370                            }
21371                            if (count == 0) {
21372                                pw.println(prefix + "No configured app linkages.");
21373                                pw.println();
21374                            }
21375                        }
21376                    }
21377                }
21378            }
21379
21380            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21381                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21382            }
21383
21384            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21385                boolean printedSomething = false;
21386                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21387                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21388                        continue;
21389                    }
21390                    if (!printedSomething) {
21391                        if (dumpState.onTitlePrinted())
21392                            pw.println();
21393                        pw.println("Registered ContentProviders:");
21394                        printedSomething = true;
21395                    }
21396                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21397                    pw.print("    "); pw.println(p.toString());
21398                }
21399                printedSomething = false;
21400                for (Map.Entry<String, PackageParser.Provider> entry :
21401                        mProvidersByAuthority.entrySet()) {
21402                    PackageParser.Provider p = entry.getValue();
21403                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21404                        continue;
21405                    }
21406                    if (!printedSomething) {
21407                        if (dumpState.onTitlePrinted())
21408                            pw.println();
21409                        pw.println("ContentProvider Authorities:");
21410                        printedSomething = true;
21411                    }
21412                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21413                    pw.print("    "); pw.println(p.toString());
21414                    if (p.info != null && p.info.applicationInfo != null) {
21415                        final String appInfo = p.info.applicationInfo.toString();
21416                        pw.print("      applicationInfo="); pw.println(appInfo);
21417                    }
21418                }
21419            }
21420
21421            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21422                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21423            }
21424
21425            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21426                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21427            }
21428
21429            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21430                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21431            }
21432
21433            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21434                if (dumpState.onTitlePrinted()) pw.println();
21435                pw.println("Package Changes:");
21436                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21437                final int K = mChangedPackages.size();
21438                for (int i = 0; i < K; i++) {
21439                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21440                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21441                    final int N = changes.size();
21442                    if (N == 0) {
21443                        pw.print("    "); pw.println("No packages changed");
21444                    } else {
21445                        for (int j = 0; j < N; j++) {
21446                            final String pkgName = changes.valueAt(j);
21447                            final int sequenceNumber = changes.keyAt(j);
21448                            pw.print("    ");
21449                            pw.print("seq=");
21450                            pw.print(sequenceNumber);
21451                            pw.print(", package=");
21452                            pw.println(pkgName);
21453                        }
21454                    }
21455                }
21456            }
21457
21458            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21459                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21460            }
21461
21462            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21463                // XXX should handle packageName != null by dumping only install data that
21464                // the given package is involved with.
21465                if (dumpState.onTitlePrinted()) pw.println();
21466
21467                try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120)) {
21468                    ipw.println();
21469                    ipw.println("Frozen packages:");
21470                    ipw.increaseIndent();
21471                    if (mFrozenPackages.size() == 0) {
21472                        ipw.println("(none)");
21473                    } else {
21474                        for (int i = 0; i < mFrozenPackages.size(); i++) {
21475                            ipw.println(mFrozenPackages.valueAt(i));
21476                        }
21477                    }
21478                    ipw.decreaseIndent();
21479                }
21480            }
21481
21482            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21483                if (dumpState.onTitlePrinted()) pw.println();
21484
21485                try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120)) {
21486                    ipw.println();
21487                    ipw.println("Loaded volumes:");
21488                    ipw.increaseIndent();
21489                    if (mLoadedVolumes.size() == 0) {
21490                        ipw.println("(none)");
21491                    } else {
21492                        for (int i = 0; i < mLoadedVolumes.size(); i++) {
21493                            ipw.println(mLoadedVolumes.valueAt(i));
21494                        }
21495                    }
21496                    ipw.decreaseIndent();
21497                }
21498            }
21499
21500            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21501                    && packageName == null) {
21502                if (dumpState.onTitlePrinted()) pw.println();
21503                pw.println("Service permissions:");
21504
21505                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21506                while (filterIterator.hasNext()) {
21507                    final ServiceIntentInfo info = filterIterator.next();
21508                    final ServiceInfo serviceInfo = info.service.info;
21509                    final String permission = serviceInfo.permission;
21510                    if (permission != null) {
21511                        pw.print("    ");
21512                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21513                        pw.print(": ");
21514                        pw.println(permission);
21515                    }
21516                }
21517            }
21518
21519            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21520                if (dumpState.onTitlePrinted()) pw.println();
21521                dumpDexoptStateLPr(pw, packageName);
21522            }
21523
21524            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21525                if (dumpState.onTitlePrinted()) pw.println();
21526                dumpCompilerStatsLPr(pw, packageName);
21527            }
21528
21529            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21530                if (dumpState.onTitlePrinted()) pw.println();
21531                mSettings.dumpReadMessagesLPr(pw, dumpState);
21532
21533                pw.println();
21534                pw.println("Package warning messages:");
21535                dumpCriticalInfo(pw, null);
21536            }
21537
21538            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21539                dumpCriticalInfo(pw, "msg,");
21540            }
21541        }
21542
21543        // PackageInstaller should be called outside of mPackages lock
21544        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21545            // XXX should handle packageName != null by dumping only install data that
21546            // the given package is involved with.
21547            if (dumpState.onTitlePrinted()) pw.println();
21548            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21549        }
21550    }
21551
21552    private void dumpProto(FileDescriptor fd) {
21553        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21554
21555        synchronized (mPackages) {
21556            final long requiredVerifierPackageToken =
21557                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21558            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21559            proto.write(
21560                    PackageServiceDumpProto.PackageShortProto.UID,
21561                    getPackageUid(
21562                            mRequiredVerifierPackage,
21563                            MATCH_DEBUG_TRIAGED_MISSING,
21564                            UserHandle.USER_SYSTEM));
21565            proto.end(requiredVerifierPackageToken);
21566
21567            if (mIntentFilterVerifierComponent != null) {
21568                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21569                final long verifierPackageToken =
21570                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21571                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21572                proto.write(
21573                        PackageServiceDumpProto.PackageShortProto.UID,
21574                        getPackageUid(
21575                                verifierPackageName,
21576                                MATCH_DEBUG_TRIAGED_MISSING,
21577                                UserHandle.USER_SYSTEM));
21578                proto.end(verifierPackageToken);
21579            }
21580
21581            dumpSharedLibrariesProto(proto);
21582            dumpFeaturesProto(proto);
21583            mSettings.dumpPackagesProto(proto);
21584            mSettings.dumpSharedUsersProto(proto);
21585            dumpCriticalInfo(proto);
21586        }
21587        proto.flush();
21588    }
21589
21590    private void dumpFeaturesProto(ProtoOutputStream proto) {
21591        synchronized (mAvailableFeatures) {
21592            final int count = mAvailableFeatures.size();
21593            for (int i = 0; i < count; i++) {
21594                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21595            }
21596        }
21597    }
21598
21599    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21600        final int count = mSharedLibraries.size();
21601        for (int i = 0; i < count; i++) {
21602            final String libName = mSharedLibraries.keyAt(i);
21603            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21604            if (versionedLib == null) {
21605                continue;
21606            }
21607            final int versionCount = versionedLib.size();
21608            for (int j = 0; j < versionCount; j++) {
21609                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21610                final long sharedLibraryToken =
21611                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21612                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21613                final boolean isJar = (libEntry.path != null);
21614                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21615                if (isJar) {
21616                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21617                } else {
21618                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21619                }
21620                proto.end(sharedLibraryToken);
21621            }
21622        }
21623    }
21624
21625    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21626        try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ")) {
21627            ipw.println();
21628            ipw.println("Dexopt state:");
21629            ipw.increaseIndent();
21630            Collection<PackageParser.Package> packages = null;
21631            if (packageName != null) {
21632                PackageParser.Package targetPackage = mPackages.get(packageName);
21633                if (targetPackage != null) {
21634                    packages = Collections.singletonList(targetPackage);
21635                } else {
21636                    ipw.println("Unable to find package: " + packageName);
21637                    return;
21638                }
21639            } else {
21640                packages = mPackages.values();
21641            }
21642
21643            for (PackageParser.Package pkg : packages) {
21644                ipw.println("[" + pkg.packageName + "]");
21645                ipw.increaseIndent();
21646                mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21647                        mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21648                ipw.decreaseIndent();
21649            }
21650        }
21651    }
21652
21653    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21654        try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ")) {
21655            ipw.println();
21656            ipw.println("Compiler stats:");
21657            ipw.increaseIndent();
21658            Collection<PackageParser.Package> packages = null;
21659            if (packageName != null) {
21660                PackageParser.Package targetPackage = mPackages.get(packageName);
21661                if (targetPackage != null) {
21662                    packages = Collections.singletonList(targetPackage);
21663                } else {
21664                    ipw.println("Unable to find package: " + packageName);
21665                    return;
21666                }
21667            } else {
21668                packages = mPackages.values();
21669            }
21670
21671            for (PackageParser.Package pkg : packages) {
21672                ipw.println("[" + pkg.packageName + "]");
21673                ipw.increaseIndent();
21674
21675                CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21676                if (stats == null) {
21677                    ipw.println("(No recorded stats)");
21678                } else {
21679                    stats.dump(ipw);
21680                }
21681                ipw.decreaseIndent();
21682            }
21683        }
21684    }
21685
21686    private String dumpDomainString(String packageName) {
21687        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21688                .getList();
21689        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21690
21691        ArraySet<String> result = new ArraySet<>();
21692        if (iviList.size() > 0) {
21693            for (IntentFilterVerificationInfo ivi : iviList) {
21694                for (String host : ivi.getDomains()) {
21695                    result.add(host);
21696                }
21697            }
21698        }
21699        if (filters != null && filters.size() > 0) {
21700            for (IntentFilter filter : filters) {
21701                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21702                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21703                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21704                    result.addAll(filter.getHostsList());
21705                }
21706            }
21707        }
21708
21709        StringBuilder sb = new StringBuilder(result.size() * 16);
21710        for (String domain : result) {
21711            if (sb.length() > 0) sb.append(" ");
21712            sb.append(domain);
21713        }
21714        return sb.toString();
21715    }
21716
21717    // ------- apps on sdcard specific code -------
21718    static final boolean DEBUG_SD_INSTALL = false;
21719
21720    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21721
21722    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21723
21724    private boolean mMediaMounted = false;
21725
21726    static String getEncryptKey() {
21727        try {
21728            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21729                    SD_ENCRYPTION_KEYSTORE_NAME);
21730            if (sdEncKey == null) {
21731                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21732                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21733                if (sdEncKey == null) {
21734                    Slog.e(TAG, "Failed to create encryption keys");
21735                    return null;
21736                }
21737            }
21738            return sdEncKey;
21739        } catch (NoSuchAlgorithmException nsae) {
21740            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21741            return null;
21742        } catch (IOException ioe) {
21743            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21744            return null;
21745        }
21746    }
21747
21748    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21749            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21750        final int size = infos.size();
21751        final String[] packageNames = new String[size];
21752        final int[] packageUids = new int[size];
21753        for (int i = 0; i < size; i++) {
21754            final ApplicationInfo info = infos.get(i);
21755            packageNames[i] = info.packageName;
21756            packageUids[i] = info.uid;
21757        }
21758        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21759                finishedReceiver);
21760    }
21761
21762    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21763            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21764        sendResourcesChangedBroadcast(mediaStatus, replacing,
21765                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21766    }
21767
21768    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21769            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21770        int size = pkgList.length;
21771        if (size > 0) {
21772            // Send broadcasts here
21773            Bundle extras = new Bundle();
21774            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21775            if (uidArr != null) {
21776                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21777            }
21778            if (replacing) {
21779                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21780            }
21781            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21782                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21783            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
21784        }
21785    }
21786
21787    private void loadPrivatePackages(final VolumeInfo vol) {
21788        mHandler.post(new Runnable() {
21789            @Override
21790            public void run() {
21791                loadPrivatePackagesInner(vol);
21792            }
21793        });
21794    }
21795
21796    private void loadPrivatePackagesInner(VolumeInfo vol) {
21797        final String volumeUuid = vol.fsUuid;
21798        if (TextUtils.isEmpty(volumeUuid)) {
21799            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21800            return;
21801        }
21802
21803        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21804        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21805        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21806
21807        final VersionInfo ver;
21808        final List<PackageSetting> packages;
21809        synchronized (mPackages) {
21810            ver = mSettings.findOrCreateVersion(volumeUuid);
21811            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21812        }
21813
21814        for (PackageSetting ps : packages) {
21815            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21816            synchronized (mInstallLock) {
21817                final PackageParser.Package pkg;
21818                try {
21819                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21820                    loaded.add(pkg.applicationInfo);
21821
21822                } catch (PackageManagerException e) {
21823                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21824                }
21825
21826                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21827                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21828                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21829                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21830                }
21831            }
21832        }
21833
21834        // Reconcile app data for all started/unlocked users
21835        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21836        final UserManager um = mContext.getSystemService(UserManager.class);
21837        UserManagerInternal umInternal = getUserManagerInternal();
21838        for (UserInfo user : um.getUsers()) {
21839            final int flags;
21840            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21841                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21842            } else if (umInternal.isUserRunning(user.id)) {
21843                flags = StorageManager.FLAG_STORAGE_DE;
21844            } else {
21845                continue;
21846            }
21847
21848            try {
21849                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21850                synchronized (mInstallLock) {
21851                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21852                }
21853            } catch (IllegalStateException e) {
21854                // Device was probably ejected, and we'll process that event momentarily
21855                Slog.w(TAG, "Failed to prepare storage: " + e);
21856            }
21857        }
21858
21859        synchronized (mPackages) {
21860            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
21861            if (sdkUpdated) {
21862                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21863                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21864            }
21865            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
21866                    mPermissionCallback);
21867
21868            // Yay, everything is now upgraded
21869            ver.forceCurrent();
21870
21871            mSettings.writeLPr();
21872        }
21873
21874        for (PackageFreezer freezer : freezers) {
21875            freezer.close();
21876        }
21877
21878        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21879        sendResourcesChangedBroadcast(true, false, loaded, null);
21880        mLoadedVolumes.add(vol.getId());
21881    }
21882
21883    private void unloadPrivatePackages(final VolumeInfo vol) {
21884        mHandler.post(new Runnable() {
21885            @Override
21886            public void run() {
21887                unloadPrivatePackagesInner(vol);
21888            }
21889        });
21890    }
21891
21892    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21893        final String volumeUuid = vol.fsUuid;
21894        if (TextUtils.isEmpty(volumeUuid)) {
21895            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21896            return;
21897        }
21898
21899        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21900        synchronized (mInstallLock) {
21901        synchronized (mPackages) {
21902            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21903            for (PackageSetting ps : packages) {
21904                if (ps.pkg == null) continue;
21905
21906                final ApplicationInfo info = ps.pkg.applicationInfo;
21907                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21908                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
21909
21910                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21911                        "unloadPrivatePackagesInner")) {
21912                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21913                            false, null)) {
21914                        unloaded.add(info);
21915                    } else {
21916                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21917                    }
21918                }
21919
21920                // Try very hard to release any references to this package
21921                // so we don't risk the system server being killed due to
21922                // open FDs
21923                AttributeCache.instance().removePackage(ps.name);
21924            }
21925
21926            mSettings.writeLPr();
21927        }
21928        }
21929
21930        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21931        sendResourcesChangedBroadcast(false, false, unloaded, null);
21932        mLoadedVolumes.remove(vol.getId());
21933
21934        // Try very hard to release any references to this path so we don't risk
21935        // the system server being killed due to open FDs
21936        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21937
21938        for (int i = 0; i < 3; i++) {
21939            System.gc();
21940            System.runFinalization();
21941        }
21942    }
21943
21944    private void assertPackageKnown(String volumeUuid, String packageName)
21945            throws PackageManagerException {
21946        synchronized (mPackages) {
21947            // Normalize package name to handle renamed packages
21948            packageName = normalizePackageNameLPr(packageName);
21949
21950            final PackageSetting ps = mSettings.mPackages.get(packageName);
21951            if (ps == null) {
21952                throw new PackageManagerException("Package " + packageName + " is unknown");
21953            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21954                throw new PackageManagerException(
21955                        "Package " + packageName + " found on unknown volume " + volumeUuid
21956                                + "; expected volume " + ps.volumeUuid);
21957            }
21958        }
21959    }
21960
21961    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21962            throws PackageManagerException {
21963        synchronized (mPackages) {
21964            // Normalize package name to handle renamed packages
21965            packageName = normalizePackageNameLPr(packageName);
21966
21967            final PackageSetting ps = mSettings.mPackages.get(packageName);
21968            if (ps == null) {
21969                throw new PackageManagerException("Package " + packageName + " is unknown");
21970            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21971                throw new PackageManagerException(
21972                        "Package " + packageName + " found on unknown volume " + volumeUuid
21973                                + "; expected volume " + ps.volumeUuid);
21974            } else if (!ps.getInstalled(userId)) {
21975                throw new PackageManagerException(
21976                        "Package " + packageName + " not installed for user " + userId);
21977            }
21978        }
21979    }
21980
21981    private List<String> collectAbsoluteCodePaths() {
21982        synchronized (mPackages) {
21983            List<String> codePaths = new ArrayList<>();
21984            final int packageCount = mSettings.mPackages.size();
21985            for (int i = 0; i < packageCount; i++) {
21986                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21987                codePaths.add(ps.codePath.getAbsolutePath());
21988            }
21989            return codePaths;
21990        }
21991    }
21992
21993    /**
21994     * Examine all apps present on given mounted volume, and destroy apps that
21995     * aren't expected, either due to uninstallation or reinstallation on
21996     * another volume.
21997     */
21998    private void reconcileApps(String volumeUuid) {
21999        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22000        List<File> filesToDelete = null;
22001
22002        final File[] files = FileUtils.listFilesOrEmpty(
22003                Environment.getDataAppDirectory(volumeUuid));
22004        for (File file : files) {
22005            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22006                    && !PackageInstallerService.isStageName(file.getName());
22007            if (!isPackage) {
22008                // Ignore entries which are not packages
22009                continue;
22010            }
22011
22012            String absolutePath = file.getAbsolutePath();
22013
22014            boolean pathValid = false;
22015            final int absoluteCodePathCount = absoluteCodePaths.size();
22016            for (int i = 0; i < absoluteCodePathCount; i++) {
22017                String absoluteCodePath = absoluteCodePaths.get(i);
22018                if (absolutePath.startsWith(absoluteCodePath)) {
22019                    pathValid = true;
22020                    break;
22021                }
22022            }
22023
22024            if (!pathValid) {
22025                if (filesToDelete == null) {
22026                    filesToDelete = new ArrayList<>();
22027                }
22028                filesToDelete.add(file);
22029            }
22030        }
22031
22032        if (filesToDelete != null) {
22033            final int fileToDeleteCount = filesToDelete.size();
22034            for (int i = 0; i < fileToDeleteCount; i++) {
22035                File fileToDelete = filesToDelete.get(i);
22036                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22037                synchronized (mInstallLock) {
22038                    removeCodePathLI(fileToDelete);
22039                }
22040            }
22041        }
22042    }
22043
22044    /**
22045     * Reconcile all app data for the given user.
22046     * <p>
22047     * Verifies that directories exist and that ownership and labeling is
22048     * correct for all installed apps on all mounted volumes.
22049     */
22050    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22051        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22052        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22053            final String volumeUuid = vol.getFsUuid();
22054            synchronized (mInstallLock) {
22055                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22056            }
22057        }
22058    }
22059
22060    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22061            boolean migrateAppData) {
22062        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22063    }
22064
22065    /**
22066     * Reconcile all app data on given mounted volume.
22067     * <p>
22068     * Destroys app data that isn't expected, either due to uninstallation or
22069     * reinstallation on another volume.
22070     * <p>
22071     * Verifies that directories exist and that ownership and labeling is
22072     * correct for all installed apps.
22073     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22074     */
22075    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22076            boolean migrateAppData, boolean onlyCoreApps) {
22077        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22078                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22079        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22080
22081        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22082        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22083
22084        // First look for stale data that doesn't belong, and check if things
22085        // have changed since we did our last restorecon
22086        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22087            if (StorageManager.isFileEncryptedNativeOrEmulated()
22088                    && !StorageManager.isUserKeyUnlocked(userId)) {
22089                throw new RuntimeException(
22090                        "Yikes, someone asked us to reconcile CE storage while " + userId
22091                                + " was still locked; this would have caused massive data loss!");
22092            }
22093
22094            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22095            for (File file : files) {
22096                final String packageName = file.getName();
22097                try {
22098                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22099                } catch (PackageManagerException e) {
22100                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22101                    try {
22102                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22103                                StorageManager.FLAG_STORAGE_CE, 0);
22104                    } catch (InstallerException e2) {
22105                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22106                    }
22107                }
22108            }
22109        }
22110        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22111            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22112            for (File file : files) {
22113                final String packageName = file.getName();
22114                try {
22115                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22116                } catch (PackageManagerException e) {
22117                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22118                    try {
22119                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22120                                StorageManager.FLAG_STORAGE_DE, 0);
22121                    } catch (InstallerException e2) {
22122                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22123                    }
22124                }
22125            }
22126        }
22127
22128        // Ensure that data directories are ready to roll for all packages
22129        // installed for this volume and user
22130        final List<PackageSetting> packages;
22131        synchronized (mPackages) {
22132            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22133        }
22134        int preparedCount = 0;
22135        for (PackageSetting ps : packages) {
22136            final String packageName = ps.name;
22137            if (ps.pkg == null) {
22138                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22139                // TODO: might be due to legacy ASEC apps; we should circle back
22140                // and reconcile again once they're scanned
22141                continue;
22142            }
22143            // Skip non-core apps if requested
22144            if (onlyCoreApps && !ps.pkg.coreApp) {
22145                result.add(packageName);
22146                continue;
22147            }
22148
22149            if (ps.getInstalled(userId)) {
22150                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22151                preparedCount++;
22152            }
22153        }
22154
22155        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22156        return result;
22157    }
22158
22159    /**
22160     * Prepare app data for the given app just after it was installed or
22161     * upgraded. This method carefully only touches users that it's installed
22162     * for, and it forces a restorecon to handle any seinfo changes.
22163     * <p>
22164     * Verifies that directories exist and that ownership and labeling is
22165     * correct for all installed apps. If there is an ownership mismatch, it
22166     * will try recovering system apps by wiping data; third-party app data is
22167     * left intact.
22168     * <p>
22169     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22170     */
22171    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22172        final PackageSetting ps;
22173        synchronized (mPackages) {
22174            ps = mSettings.mPackages.get(pkg.packageName);
22175            mSettings.writeKernelMappingLPr(ps);
22176        }
22177
22178        final UserManager um = mContext.getSystemService(UserManager.class);
22179        UserManagerInternal umInternal = getUserManagerInternal();
22180        for (UserInfo user : um.getUsers()) {
22181            final int flags;
22182            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22183                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22184            } else if (umInternal.isUserRunning(user.id)) {
22185                flags = StorageManager.FLAG_STORAGE_DE;
22186            } else {
22187                continue;
22188            }
22189
22190            if (ps.getInstalled(user.id)) {
22191                // TODO: when user data is locked, mark that we're still dirty
22192                prepareAppDataLIF(pkg, user.id, flags);
22193            }
22194        }
22195    }
22196
22197    /**
22198     * Prepare app data for the given app.
22199     * <p>
22200     * Verifies that directories exist and that ownership and labeling is
22201     * correct for all installed apps. If there is an ownership mismatch, this
22202     * will try recovering system apps by wiping data; third-party app data is
22203     * left intact.
22204     */
22205    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22206        if (pkg == null) {
22207            Slog.wtf(TAG, "Package was null!", new Throwable());
22208            return;
22209        }
22210        prepareAppDataLeafLIF(pkg, userId, flags);
22211        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22212        for (int i = 0; i < childCount; i++) {
22213            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22214        }
22215    }
22216
22217    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22218            boolean maybeMigrateAppData) {
22219        prepareAppDataLIF(pkg, userId, flags);
22220
22221        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22222            // We may have just shuffled around app data directories, so
22223            // prepare them one more time
22224            prepareAppDataLIF(pkg, userId, flags);
22225        }
22226    }
22227
22228    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22229        if (DEBUG_APP_DATA) {
22230            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22231                    + Integer.toHexString(flags));
22232        }
22233
22234        final String volumeUuid = pkg.volumeUuid;
22235        final String packageName = pkg.packageName;
22236        final ApplicationInfo app = pkg.applicationInfo;
22237        final int appId = UserHandle.getAppId(app.uid);
22238
22239        Preconditions.checkNotNull(app.seInfo);
22240
22241        long ceDataInode = -1;
22242        try {
22243            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22244                    appId, app.seInfo, app.targetSdkVersion);
22245        } catch (InstallerException e) {
22246            if (app.isSystemApp()) {
22247                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22248                        + ", but trying to recover: " + e);
22249                destroyAppDataLeafLIF(pkg, userId, flags);
22250                try {
22251                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22252                            appId, app.seInfo, app.targetSdkVersion);
22253                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22254                } catch (InstallerException e2) {
22255                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22256                }
22257            } else {
22258                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22259            }
22260        }
22261        // Prepare the application profiles only for upgrades and first boot (so that we don't
22262        // repeat the same operation at each boot).
22263        // We only have to cover the upgrade and first boot here because for app installs we
22264        // prepare the profiles before invoking dexopt (in installPackageLI).
22265        //
22266        // We also have to cover non system users because we do not call the usual install package
22267        // methods for them.
22268        if (mIsUpgrade || mFirstBoot || (userId != UserHandle.USER_SYSTEM)) {
22269            mArtManagerService.prepareAppProfiles(pkg, userId);
22270        }
22271
22272        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22273            // TODO: mark this structure as dirty so we persist it!
22274            synchronized (mPackages) {
22275                final PackageSetting ps = mSettings.mPackages.get(packageName);
22276                if (ps != null) {
22277                    ps.setCeDataInode(ceDataInode, userId);
22278                }
22279            }
22280        }
22281
22282        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22283    }
22284
22285    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22286        if (pkg == null) {
22287            Slog.wtf(TAG, "Package was null!", new Throwable());
22288            return;
22289        }
22290        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22291        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22292        for (int i = 0; i < childCount; i++) {
22293            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22294        }
22295    }
22296
22297    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22298        final String volumeUuid = pkg.volumeUuid;
22299        final String packageName = pkg.packageName;
22300        final ApplicationInfo app = pkg.applicationInfo;
22301
22302        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22303            // Create a native library symlink only if we have native libraries
22304            // and if the native libraries are 32 bit libraries. We do not provide
22305            // this symlink for 64 bit libraries.
22306            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22307                final String nativeLibPath = app.nativeLibraryDir;
22308                try {
22309                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22310                            nativeLibPath, userId);
22311                } catch (InstallerException e) {
22312                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22313                }
22314            }
22315        }
22316    }
22317
22318    /**
22319     * For system apps on non-FBE devices, this method migrates any existing
22320     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22321     * requested by the app.
22322     */
22323    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22324        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
22325                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22326            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22327                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22328            try {
22329                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22330                        storageTarget);
22331            } catch (InstallerException e) {
22332                logCriticalInfo(Log.WARN,
22333                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22334            }
22335            return true;
22336        } else {
22337            return false;
22338        }
22339    }
22340
22341    public PackageFreezer freezePackage(String packageName, String killReason) {
22342        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22343    }
22344
22345    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22346        return new PackageFreezer(packageName, userId, killReason);
22347    }
22348
22349    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22350            String killReason) {
22351        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22352    }
22353
22354    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22355            String killReason) {
22356        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22357            return new PackageFreezer();
22358        } else {
22359            return freezePackage(packageName, userId, killReason);
22360        }
22361    }
22362
22363    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22364            String killReason) {
22365        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22366    }
22367
22368    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22369            String killReason) {
22370        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22371            return new PackageFreezer();
22372        } else {
22373            return freezePackage(packageName, userId, killReason);
22374        }
22375    }
22376
22377    /**
22378     * Class that freezes and kills the given package upon creation, and
22379     * unfreezes it upon closing. This is typically used when doing surgery on
22380     * app code/data to prevent the app from running while you're working.
22381     */
22382    private class PackageFreezer implements AutoCloseable {
22383        private final String mPackageName;
22384        private final PackageFreezer[] mChildren;
22385
22386        private final boolean mWeFroze;
22387
22388        private final AtomicBoolean mClosed = new AtomicBoolean();
22389        private final CloseGuard mCloseGuard = CloseGuard.get();
22390
22391        /**
22392         * Create and return a stub freezer that doesn't actually do anything,
22393         * typically used when someone requested
22394         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22395         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22396         */
22397        public PackageFreezer() {
22398            mPackageName = null;
22399            mChildren = null;
22400            mWeFroze = false;
22401            mCloseGuard.open("close");
22402        }
22403
22404        public PackageFreezer(String packageName, int userId, String killReason) {
22405            synchronized (mPackages) {
22406                mPackageName = packageName;
22407                mWeFroze = mFrozenPackages.add(mPackageName);
22408
22409                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22410                if (ps != null) {
22411                    killApplication(ps.name, ps.appId, userId, killReason);
22412                }
22413
22414                final PackageParser.Package p = mPackages.get(packageName);
22415                if (p != null && p.childPackages != null) {
22416                    final int N = p.childPackages.size();
22417                    mChildren = new PackageFreezer[N];
22418                    for (int i = 0; i < N; i++) {
22419                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22420                                userId, killReason);
22421                    }
22422                } else {
22423                    mChildren = null;
22424                }
22425            }
22426            mCloseGuard.open("close");
22427        }
22428
22429        @Override
22430        protected void finalize() throws Throwable {
22431            try {
22432                if (mCloseGuard != null) {
22433                    mCloseGuard.warnIfOpen();
22434                }
22435
22436                close();
22437            } finally {
22438                super.finalize();
22439            }
22440        }
22441
22442        @Override
22443        public void close() {
22444            mCloseGuard.close();
22445            if (mClosed.compareAndSet(false, true)) {
22446                synchronized (mPackages) {
22447                    if (mWeFroze) {
22448                        mFrozenPackages.remove(mPackageName);
22449                    }
22450
22451                    if (mChildren != null) {
22452                        for (PackageFreezer freezer : mChildren) {
22453                            freezer.close();
22454                        }
22455                    }
22456                }
22457            }
22458        }
22459    }
22460
22461    /**
22462     * Verify that given package is currently frozen.
22463     */
22464    private void checkPackageFrozen(String packageName) {
22465        synchronized (mPackages) {
22466            if (!mFrozenPackages.contains(packageName)) {
22467                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22468            }
22469        }
22470    }
22471
22472    @Override
22473    public int movePackage(final String packageName, final String volumeUuid) {
22474        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22475
22476        final int callingUid = Binder.getCallingUid();
22477        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22478        final int moveId = mNextMoveId.getAndIncrement();
22479        mHandler.post(new Runnable() {
22480            @Override
22481            public void run() {
22482                try {
22483                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22484                } catch (PackageManagerException e) {
22485                    Slog.w(TAG, "Failed to move " + packageName, e);
22486                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22487                }
22488            }
22489        });
22490        return moveId;
22491    }
22492
22493    private void movePackageInternal(final String packageName, final String volumeUuid,
22494            final int moveId, final int callingUid, UserHandle user)
22495                    throws PackageManagerException {
22496        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22497        final PackageManager pm = mContext.getPackageManager();
22498
22499        final boolean currentAsec;
22500        final String currentVolumeUuid;
22501        final File codeFile;
22502        final String installerPackageName;
22503        final String packageAbiOverride;
22504        final int appId;
22505        final String seinfo;
22506        final String label;
22507        final int targetSdkVersion;
22508        final PackageFreezer freezer;
22509        final int[] installedUserIds;
22510
22511        // reader
22512        synchronized (mPackages) {
22513            final PackageParser.Package pkg = mPackages.get(packageName);
22514            final PackageSetting ps = mSettings.mPackages.get(packageName);
22515            if (pkg == null
22516                    || ps == null
22517                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22518                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22519            }
22520            if (pkg.applicationInfo.isSystemApp()) {
22521                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22522                        "Cannot move system application");
22523            }
22524
22525            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22526            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22527                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22528            if (isInternalStorage && !allow3rdPartyOnInternal) {
22529                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22530                        "3rd party apps are not allowed on internal storage");
22531            }
22532
22533            if (pkg.applicationInfo.isExternalAsec()) {
22534                currentAsec = true;
22535                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22536            } else if (pkg.applicationInfo.isForwardLocked()) {
22537                currentAsec = true;
22538                currentVolumeUuid = "forward_locked";
22539            } else {
22540                currentAsec = false;
22541                currentVolumeUuid = ps.volumeUuid;
22542
22543                final File probe = new File(pkg.codePath);
22544                final File probeOat = new File(probe, "oat");
22545                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22546                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22547                            "Move only supported for modern cluster style installs");
22548                }
22549            }
22550
22551            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22552                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22553                        "Package already moved to " + volumeUuid);
22554            }
22555            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22556                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22557                        "Device admin cannot be moved");
22558            }
22559
22560            if (mFrozenPackages.contains(packageName)) {
22561                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22562                        "Failed to move already frozen package");
22563            }
22564
22565            codeFile = new File(pkg.codePath);
22566            installerPackageName = ps.installerPackageName;
22567            packageAbiOverride = ps.cpuAbiOverrideString;
22568            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22569            seinfo = pkg.applicationInfo.seInfo;
22570            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22571            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22572            freezer = freezePackage(packageName, "movePackageInternal");
22573            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22574        }
22575
22576        final Bundle extras = new Bundle();
22577        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22578        extras.putString(Intent.EXTRA_TITLE, label);
22579        mMoveCallbacks.notifyCreated(moveId, extras);
22580
22581        int installFlags;
22582        final boolean moveCompleteApp;
22583        final File measurePath;
22584
22585        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22586            installFlags = INSTALL_INTERNAL;
22587            moveCompleteApp = !currentAsec;
22588            measurePath = Environment.getDataAppDirectory(volumeUuid);
22589        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22590            installFlags = INSTALL_EXTERNAL;
22591            moveCompleteApp = false;
22592            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22593        } else {
22594            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22595            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22596                    || !volume.isMountedWritable()) {
22597                freezer.close();
22598                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22599                        "Move location not mounted private volume");
22600            }
22601
22602            Preconditions.checkState(!currentAsec);
22603
22604            installFlags = INSTALL_INTERNAL;
22605            moveCompleteApp = true;
22606            measurePath = Environment.getDataAppDirectory(volumeUuid);
22607        }
22608
22609        // If we're moving app data around, we need all the users unlocked
22610        if (moveCompleteApp) {
22611            for (int userId : installedUserIds) {
22612                if (StorageManager.isFileEncryptedNativeOrEmulated()
22613                        && !StorageManager.isUserKeyUnlocked(userId)) {
22614                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22615                            "User " + userId + " must be unlocked");
22616                }
22617            }
22618        }
22619
22620        final PackageStats stats = new PackageStats(null, -1);
22621        synchronized (mInstaller) {
22622            for (int userId : installedUserIds) {
22623                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22624                    freezer.close();
22625                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22626                            "Failed to measure package size");
22627                }
22628            }
22629        }
22630
22631        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22632                + stats.dataSize);
22633
22634        final long startFreeBytes = measurePath.getUsableSpace();
22635        final long sizeBytes;
22636        if (moveCompleteApp) {
22637            sizeBytes = stats.codeSize + stats.dataSize;
22638        } else {
22639            sizeBytes = stats.codeSize;
22640        }
22641
22642        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22643            freezer.close();
22644            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22645                    "Not enough free space to move");
22646        }
22647
22648        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22649
22650        final CountDownLatch installedLatch = new CountDownLatch(1);
22651        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22652            @Override
22653            public void onUserActionRequired(Intent intent) throws RemoteException {
22654                throw new IllegalStateException();
22655            }
22656
22657            @Override
22658            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22659                    Bundle extras) throws RemoteException {
22660                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22661                        + PackageManager.installStatusToString(returnCode, msg));
22662
22663                installedLatch.countDown();
22664                freezer.close();
22665
22666                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22667                switch (status) {
22668                    case PackageInstaller.STATUS_SUCCESS:
22669                        mMoveCallbacks.notifyStatusChanged(moveId,
22670                                PackageManager.MOVE_SUCCEEDED);
22671                        break;
22672                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22673                        mMoveCallbacks.notifyStatusChanged(moveId,
22674                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22675                        break;
22676                    default:
22677                        mMoveCallbacks.notifyStatusChanged(moveId,
22678                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22679                        break;
22680                }
22681            }
22682        };
22683
22684        final MoveInfo move;
22685        if (moveCompleteApp) {
22686            // Kick off a thread to report progress estimates
22687            new Thread() {
22688                @Override
22689                public void run() {
22690                    while (true) {
22691                        try {
22692                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22693                                break;
22694                            }
22695                        } catch (InterruptedException ignored) {
22696                        }
22697
22698                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22699                        final int progress = 10 + (int) MathUtils.constrain(
22700                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22701                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22702                    }
22703                }
22704            }.start();
22705
22706            final String dataAppName = codeFile.getName();
22707            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22708                    dataAppName, appId, seinfo, targetSdkVersion);
22709        } else {
22710            move = null;
22711        }
22712
22713        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22714
22715        final Message msg = mHandler.obtainMessage(INIT_COPY);
22716        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22717        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22718                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22719                packageAbiOverride, null /*grantedPermissions*/,
22720                PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
22721        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22722        msg.obj = params;
22723
22724        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22725                System.identityHashCode(msg.obj));
22726        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22727                System.identityHashCode(msg.obj));
22728
22729        mHandler.sendMessage(msg);
22730    }
22731
22732    @Override
22733    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22734        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22735
22736        final int realMoveId = mNextMoveId.getAndIncrement();
22737        final Bundle extras = new Bundle();
22738        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22739        mMoveCallbacks.notifyCreated(realMoveId, extras);
22740
22741        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22742            @Override
22743            public void onCreated(int moveId, Bundle extras) {
22744                // Ignored
22745            }
22746
22747            @Override
22748            public void onStatusChanged(int moveId, int status, long estMillis) {
22749                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22750            }
22751        };
22752
22753        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22754        storage.setPrimaryStorageUuid(volumeUuid, callback);
22755        return realMoveId;
22756    }
22757
22758    @Override
22759    public int getMoveStatus(int moveId) {
22760        mContext.enforceCallingOrSelfPermission(
22761                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22762        return mMoveCallbacks.mLastStatus.get(moveId);
22763    }
22764
22765    @Override
22766    public void registerMoveCallback(IPackageMoveObserver callback) {
22767        mContext.enforceCallingOrSelfPermission(
22768                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22769        mMoveCallbacks.register(callback);
22770    }
22771
22772    @Override
22773    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22774        mContext.enforceCallingOrSelfPermission(
22775                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22776        mMoveCallbacks.unregister(callback);
22777    }
22778
22779    @Override
22780    public boolean setInstallLocation(int loc) {
22781        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22782                null);
22783        if (getInstallLocation() == loc) {
22784            return true;
22785        }
22786        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22787                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22788            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22789                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22790            return true;
22791        }
22792        return false;
22793   }
22794
22795    @Override
22796    public int getInstallLocation() {
22797        // allow instant app access
22798        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22799                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22800                PackageHelper.APP_INSTALL_AUTO);
22801    }
22802
22803    /** Called by UserManagerService */
22804    void cleanUpUser(UserManagerService userManager, int userHandle) {
22805        synchronized (mPackages) {
22806            mDirtyUsers.remove(userHandle);
22807            mUserNeedsBadging.delete(userHandle);
22808            mSettings.removeUserLPw(userHandle);
22809            mPendingBroadcasts.remove(userHandle);
22810            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22811            removeUnusedPackagesLPw(userManager, userHandle);
22812        }
22813    }
22814
22815    /**
22816     * We're removing userHandle and would like to remove any downloaded packages
22817     * that are no longer in use by any other user.
22818     * @param userHandle the user being removed
22819     */
22820    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22821        final boolean DEBUG_CLEAN_APKS = false;
22822        int [] users = userManager.getUserIds();
22823        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22824        while (psit.hasNext()) {
22825            PackageSetting ps = psit.next();
22826            if (ps.pkg == null) {
22827                continue;
22828            }
22829            final String packageName = ps.pkg.packageName;
22830            // Skip over if system app
22831            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22832                continue;
22833            }
22834            if (DEBUG_CLEAN_APKS) {
22835                Slog.i(TAG, "Checking package " + packageName);
22836            }
22837            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22838            if (keep) {
22839                if (DEBUG_CLEAN_APKS) {
22840                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22841                }
22842            } else {
22843                for (int i = 0; i < users.length; i++) {
22844                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22845                        keep = true;
22846                        if (DEBUG_CLEAN_APKS) {
22847                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22848                                    + users[i]);
22849                        }
22850                        break;
22851                    }
22852                }
22853            }
22854            if (!keep) {
22855                if (DEBUG_CLEAN_APKS) {
22856                    Slog.i(TAG, "  Removing package " + packageName);
22857                }
22858                mHandler.post(new Runnable() {
22859                    public void run() {
22860                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22861                                userHandle, 0);
22862                    } //end run
22863                });
22864            }
22865        }
22866    }
22867
22868    /** Called by UserManagerService */
22869    void createNewUser(int userId, String[] disallowedPackages) {
22870        synchronized (mInstallLock) {
22871            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22872        }
22873        synchronized (mPackages) {
22874            scheduleWritePackageRestrictionsLocked(userId);
22875            scheduleWritePackageListLocked(userId);
22876            applyFactoryDefaultBrowserLPw(userId);
22877            primeDomainVerificationsLPw(userId);
22878        }
22879    }
22880
22881    void onNewUserCreated(final int userId) {
22882        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22883        synchronized(mPackages) {
22884            // If permission review for legacy apps is required, we represent
22885            // dagerous permissions for such apps as always granted runtime
22886            // permissions to keep per user flag state whether review is needed.
22887            // Hence, if a new user is added we have to propagate dangerous
22888            // permission grants for these legacy apps.
22889            if (mSettings.mPermissions.mPermissionReviewRequired) {
22890// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
22891                mPermissionManager.updateAllPermissions(
22892                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
22893                        mPermissionCallback);
22894            }
22895        }
22896    }
22897
22898    @Override
22899    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22900        mContext.enforceCallingOrSelfPermission(
22901                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22902                "Only package verification agents can read the verifier device identity");
22903
22904        synchronized (mPackages) {
22905            return mSettings.getVerifierDeviceIdentityLPw();
22906        }
22907    }
22908
22909    @Override
22910    public void setPermissionEnforced(String permission, boolean enforced) {
22911        // TODO: Now that we no longer change GID for storage, this should to away.
22912        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22913                "setPermissionEnforced");
22914        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22915            synchronized (mPackages) {
22916                if (mSettings.mReadExternalStorageEnforced == null
22917                        || mSettings.mReadExternalStorageEnforced != enforced) {
22918                    mSettings.mReadExternalStorageEnforced =
22919                            enforced ? Boolean.TRUE : Boolean.FALSE;
22920                    mSettings.writeLPr();
22921                }
22922            }
22923            // kill any non-foreground processes so we restart them and
22924            // grant/revoke the GID.
22925            final IActivityManager am = ActivityManager.getService();
22926            if (am != null) {
22927                final long token = Binder.clearCallingIdentity();
22928                try {
22929                    am.killProcessesBelowForeground("setPermissionEnforcement");
22930                } catch (RemoteException e) {
22931                } finally {
22932                    Binder.restoreCallingIdentity(token);
22933                }
22934            }
22935        } else {
22936            throw new IllegalArgumentException("No selective enforcement for " + permission);
22937        }
22938    }
22939
22940    @Override
22941    @Deprecated
22942    public boolean isPermissionEnforced(String permission) {
22943        // allow instant applications
22944        return true;
22945    }
22946
22947    @Override
22948    public boolean isStorageLow() {
22949        // allow instant applications
22950        final long token = Binder.clearCallingIdentity();
22951        try {
22952            final DeviceStorageMonitorInternal
22953                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22954            if (dsm != null) {
22955                return dsm.isMemoryLow();
22956            } else {
22957                return false;
22958            }
22959        } finally {
22960            Binder.restoreCallingIdentity(token);
22961        }
22962    }
22963
22964    @Override
22965    public IPackageInstaller getPackageInstaller() {
22966        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
22967            return null;
22968        }
22969        return mInstallerService;
22970    }
22971
22972    @Override
22973    public IArtManager getArtManager() {
22974        return mArtManagerService;
22975    }
22976
22977    private boolean userNeedsBadging(int userId) {
22978        int index = mUserNeedsBadging.indexOfKey(userId);
22979        if (index < 0) {
22980            final UserInfo userInfo;
22981            final long token = Binder.clearCallingIdentity();
22982            try {
22983                userInfo = sUserManager.getUserInfo(userId);
22984            } finally {
22985                Binder.restoreCallingIdentity(token);
22986            }
22987            final boolean b;
22988            if (userInfo != null && userInfo.isManagedProfile()) {
22989                b = true;
22990            } else {
22991                b = false;
22992            }
22993            mUserNeedsBadging.put(userId, b);
22994            return b;
22995        }
22996        return mUserNeedsBadging.valueAt(index);
22997    }
22998
22999    @Override
23000    public KeySet getKeySetByAlias(String packageName, String alias) {
23001        if (packageName == null || alias == null) {
23002            return null;
23003        }
23004        synchronized(mPackages) {
23005            final PackageParser.Package pkg = mPackages.get(packageName);
23006            if (pkg == null) {
23007                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23008                throw new IllegalArgumentException("Unknown package: " + packageName);
23009            }
23010            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23011            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
23012                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
23013                throw new IllegalArgumentException("Unknown package: " + packageName);
23014            }
23015            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23016            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23017        }
23018    }
23019
23020    @Override
23021    public KeySet getSigningKeySet(String packageName) {
23022        if (packageName == null) {
23023            return null;
23024        }
23025        synchronized(mPackages) {
23026            final int callingUid = Binder.getCallingUid();
23027            final int callingUserId = UserHandle.getUserId(callingUid);
23028            final PackageParser.Package pkg = mPackages.get(packageName);
23029            if (pkg == null) {
23030                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23031                throw new IllegalArgumentException("Unknown package: " + packageName);
23032            }
23033            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23034            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23035                // filter and pretend the package doesn't exist
23036                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23037                        + ", uid:" + callingUid);
23038                throw new IllegalArgumentException("Unknown package: " + packageName);
23039            }
23040            if (pkg.applicationInfo.uid != callingUid
23041                    && Process.SYSTEM_UID != callingUid) {
23042                throw new SecurityException("May not access signing KeySet of other apps.");
23043            }
23044            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23045            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23046        }
23047    }
23048
23049    @Override
23050    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23051        final int callingUid = Binder.getCallingUid();
23052        if (getInstantAppPackageName(callingUid) != null) {
23053            return false;
23054        }
23055        if (packageName == null || ks == null) {
23056            return false;
23057        }
23058        synchronized(mPackages) {
23059            final PackageParser.Package pkg = mPackages.get(packageName);
23060            if (pkg == null
23061                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23062                            UserHandle.getUserId(callingUid))) {
23063                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23064                throw new IllegalArgumentException("Unknown package: " + packageName);
23065            }
23066            IBinder ksh = ks.getToken();
23067            if (ksh instanceof KeySetHandle) {
23068                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23069                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23070            }
23071            return false;
23072        }
23073    }
23074
23075    @Override
23076    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23077        final int callingUid = Binder.getCallingUid();
23078        if (getInstantAppPackageName(callingUid) != null) {
23079            return false;
23080        }
23081        if (packageName == null || ks == null) {
23082            return false;
23083        }
23084        synchronized(mPackages) {
23085            final PackageParser.Package pkg = mPackages.get(packageName);
23086            if (pkg == null
23087                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23088                            UserHandle.getUserId(callingUid))) {
23089                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23090                throw new IllegalArgumentException("Unknown package: " + packageName);
23091            }
23092            IBinder ksh = ks.getToken();
23093            if (ksh instanceof KeySetHandle) {
23094                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23095                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23096            }
23097            return false;
23098        }
23099    }
23100
23101    private void deletePackageIfUnusedLPr(final String packageName) {
23102        PackageSetting ps = mSettings.mPackages.get(packageName);
23103        if (ps == null) {
23104            return;
23105        }
23106        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23107            // TODO Implement atomic delete if package is unused
23108            // It is currently possible that the package will be deleted even if it is installed
23109            // after this method returns.
23110            mHandler.post(new Runnable() {
23111                public void run() {
23112                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23113                            0, PackageManager.DELETE_ALL_USERS);
23114                }
23115            });
23116        }
23117    }
23118
23119    /**
23120     * Check and throw if the given before/after packages would be considered a
23121     * downgrade.
23122     */
23123    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23124            throws PackageManagerException {
23125        if (after.getLongVersionCode() < before.getLongVersionCode()) {
23126            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23127                    "Update version code " + after.versionCode + " is older than current "
23128                    + before.getLongVersionCode());
23129        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
23130            if (after.baseRevisionCode < before.baseRevisionCode) {
23131                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23132                        "Update base revision code " + after.baseRevisionCode
23133                        + " is older than current " + before.baseRevisionCode);
23134            }
23135
23136            if (!ArrayUtils.isEmpty(after.splitNames)) {
23137                for (int i = 0; i < after.splitNames.length; i++) {
23138                    final String splitName = after.splitNames[i];
23139                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23140                    if (j != -1) {
23141                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23142                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23143                                    "Update split " + splitName + " revision code "
23144                                    + after.splitRevisionCodes[i] + " is older than current "
23145                                    + before.splitRevisionCodes[j]);
23146                        }
23147                    }
23148                }
23149            }
23150        }
23151    }
23152
23153    private static class MoveCallbacks extends Handler {
23154        private static final int MSG_CREATED = 1;
23155        private static final int MSG_STATUS_CHANGED = 2;
23156
23157        private final RemoteCallbackList<IPackageMoveObserver>
23158                mCallbacks = new RemoteCallbackList<>();
23159
23160        private final SparseIntArray mLastStatus = new SparseIntArray();
23161
23162        public MoveCallbacks(Looper looper) {
23163            super(looper);
23164        }
23165
23166        public void register(IPackageMoveObserver callback) {
23167            mCallbacks.register(callback);
23168        }
23169
23170        public void unregister(IPackageMoveObserver callback) {
23171            mCallbacks.unregister(callback);
23172        }
23173
23174        @Override
23175        public void handleMessage(Message msg) {
23176            final SomeArgs args = (SomeArgs) msg.obj;
23177            final int n = mCallbacks.beginBroadcast();
23178            for (int i = 0; i < n; i++) {
23179                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23180                try {
23181                    invokeCallback(callback, msg.what, args);
23182                } catch (RemoteException ignored) {
23183                }
23184            }
23185            mCallbacks.finishBroadcast();
23186            args.recycle();
23187        }
23188
23189        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23190                throws RemoteException {
23191            switch (what) {
23192                case MSG_CREATED: {
23193                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23194                    break;
23195                }
23196                case MSG_STATUS_CHANGED: {
23197                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23198                    break;
23199                }
23200            }
23201        }
23202
23203        private void notifyCreated(int moveId, Bundle extras) {
23204            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23205
23206            final SomeArgs args = SomeArgs.obtain();
23207            args.argi1 = moveId;
23208            args.arg2 = extras;
23209            obtainMessage(MSG_CREATED, args).sendToTarget();
23210        }
23211
23212        private void notifyStatusChanged(int moveId, int status) {
23213            notifyStatusChanged(moveId, status, -1);
23214        }
23215
23216        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23217            Slog.v(TAG, "Move " + moveId + " status " + status);
23218
23219            final SomeArgs args = SomeArgs.obtain();
23220            args.argi1 = moveId;
23221            args.argi2 = status;
23222            args.arg3 = estMillis;
23223            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23224
23225            synchronized (mLastStatus) {
23226                mLastStatus.put(moveId, status);
23227            }
23228        }
23229    }
23230
23231    private final static class OnPermissionChangeListeners extends Handler {
23232        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23233
23234        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23235                new RemoteCallbackList<>();
23236
23237        public OnPermissionChangeListeners(Looper looper) {
23238            super(looper);
23239        }
23240
23241        @Override
23242        public void handleMessage(Message msg) {
23243            switch (msg.what) {
23244                case MSG_ON_PERMISSIONS_CHANGED: {
23245                    final int uid = msg.arg1;
23246                    handleOnPermissionsChanged(uid);
23247                } break;
23248            }
23249        }
23250
23251        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23252            mPermissionListeners.register(listener);
23253
23254        }
23255
23256        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23257            mPermissionListeners.unregister(listener);
23258        }
23259
23260        public void onPermissionsChanged(int uid) {
23261            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23262                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23263            }
23264        }
23265
23266        private void handleOnPermissionsChanged(int uid) {
23267            final int count = mPermissionListeners.beginBroadcast();
23268            try {
23269                for (int i = 0; i < count; i++) {
23270                    IOnPermissionsChangeListener callback = mPermissionListeners
23271                            .getBroadcastItem(i);
23272                    try {
23273                        callback.onPermissionsChanged(uid);
23274                    } catch (RemoteException e) {
23275                        Log.e(TAG, "Permission listener is dead", e);
23276                    }
23277                }
23278            } finally {
23279                mPermissionListeners.finishBroadcast();
23280            }
23281        }
23282    }
23283
23284    private class PackageManagerNative extends IPackageManagerNative.Stub {
23285        @Override
23286        public String[] getNamesForUids(int[] uids) throws RemoteException {
23287            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23288            // massage results so they can be parsed by the native binder
23289            for (int i = results.length - 1; i >= 0; --i) {
23290                if (results[i] == null) {
23291                    results[i] = "";
23292                }
23293            }
23294            return results;
23295        }
23296
23297        // NB: this differentiates between preloads and sideloads
23298        @Override
23299        public String getInstallerForPackage(String packageName) throws RemoteException {
23300            final String installerName = getInstallerPackageName(packageName);
23301            if (!TextUtils.isEmpty(installerName)) {
23302                return installerName;
23303            }
23304            // differentiate between preload and sideload
23305            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23306            ApplicationInfo appInfo = getApplicationInfo(packageName,
23307                                    /*flags*/ 0,
23308                                    /*userId*/ callingUser);
23309            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23310                return "preload";
23311            }
23312            return "";
23313        }
23314
23315        @Override
23316        public long getVersionCodeForPackage(String packageName) throws RemoteException {
23317            try {
23318                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23319                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23320                if (pInfo != null) {
23321                    return pInfo.getLongVersionCode();
23322                }
23323            } catch (Exception e) {
23324            }
23325            return 0;
23326        }
23327    }
23328
23329    private class PackageManagerInternalImpl extends PackageManagerInternal {
23330        @Override
23331        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23332                int flagValues, int userId) {
23333            PackageManagerService.this.updatePermissionFlags(
23334                    permName, packageName, flagMask, flagValues, userId);
23335        }
23336
23337        @Override
23338        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23339            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23340        }
23341
23342        @Override
23343        public boolean isInstantApp(String packageName, int userId) {
23344            return PackageManagerService.this.isInstantApp(packageName, userId);
23345        }
23346
23347        @Override
23348        public String getInstantAppPackageName(int uid) {
23349            return PackageManagerService.this.getInstantAppPackageName(uid);
23350        }
23351
23352        @Override
23353        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23354            synchronized (mPackages) {
23355                return PackageManagerService.this.filterAppAccessLPr(
23356                        (PackageSetting) pkg.mExtras, callingUid, userId);
23357            }
23358        }
23359
23360        @Override
23361        public PackageParser.Package getPackage(String packageName) {
23362            synchronized (mPackages) {
23363                packageName = resolveInternalPackageNameLPr(
23364                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23365                return mPackages.get(packageName);
23366            }
23367        }
23368
23369        @Override
23370        public PackageList getPackageList(PackageListObserver observer) {
23371            synchronized (mPackages) {
23372                final int N = mPackages.size();
23373                final ArrayList<String> list = new ArrayList<>(N);
23374                for (int i = 0; i < N; i++) {
23375                    list.add(mPackages.keyAt(i));
23376                }
23377                final PackageList packageList = new PackageList(list, observer);
23378                if (observer != null) {
23379                    mPackageListObservers.add(packageList);
23380                }
23381                return packageList;
23382            }
23383        }
23384
23385        @Override
23386        public void removePackageListObserver(PackageListObserver observer) {
23387            synchronized (mPackages) {
23388                mPackageListObservers.remove(observer);
23389            }
23390        }
23391
23392        @Override
23393        public PackageParser.Package getDisabledPackage(String packageName) {
23394            synchronized (mPackages) {
23395                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23396                return (ps != null) ? ps.pkg : null;
23397            }
23398        }
23399
23400        @Override
23401        public String getKnownPackageName(int knownPackage, int userId) {
23402            switch(knownPackage) {
23403                case PackageManagerInternal.PACKAGE_BROWSER:
23404                    return getDefaultBrowserPackageName(userId);
23405                case PackageManagerInternal.PACKAGE_INSTALLER:
23406                    return mRequiredInstallerPackage;
23407                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23408                    return mSetupWizardPackage;
23409                case PackageManagerInternal.PACKAGE_SYSTEM:
23410                    return "android";
23411                case PackageManagerInternal.PACKAGE_VERIFIER:
23412                    return mRequiredVerifierPackage;
23413                case PackageManagerInternal.PACKAGE_SYSTEM_TEXT_CLASSIFIER:
23414                    return mSystemTextClassifierPackage;
23415            }
23416            return null;
23417        }
23418
23419        @Override
23420        public boolean isResolveActivityComponent(ComponentInfo component) {
23421            return mResolveActivity.packageName.equals(component.packageName)
23422                    && mResolveActivity.name.equals(component.name);
23423        }
23424
23425        @Override
23426        public void setLocationPackagesProvider(PackagesProvider provider) {
23427            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23428        }
23429
23430        @Override
23431        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23432            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23433        }
23434
23435        @Override
23436        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23437            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23438        }
23439
23440        @Override
23441        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23442            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23443        }
23444
23445        @Override
23446        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23447            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23448        }
23449
23450        @Override
23451        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23452            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23453        }
23454
23455        @Override
23456        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23457            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23458        }
23459
23460        @Override
23461        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23462            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23463        }
23464
23465        @Override
23466        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23467            synchronized (mPackages) {
23468                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23469            }
23470            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23471        }
23472
23473        @Override
23474        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23475            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23476                    packageName, userId);
23477        }
23478
23479        @Override
23480        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23481            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23482                    packageName, userId);
23483        }
23484
23485        @Override
23486        public void setKeepUninstalledPackages(final List<String> packageList) {
23487            Preconditions.checkNotNull(packageList);
23488            List<String> removedFromList = null;
23489            synchronized (mPackages) {
23490                if (mKeepUninstalledPackages != null) {
23491                    final int packagesCount = mKeepUninstalledPackages.size();
23492                    for (int i = 0; i < packagesCount; i++) {
23493                        String oldPackage = mKeepUninstalledPackages.get(i);
23494                        if (packageList != null && packageList.contains(oldPackage)) {
23495                            continue;
23496                        }
23497                        if (removedFromList == null) {
23498                            removedFromList = new ArrayList<>();
23499                        }
23500                        removedFromList.add(oldPackage);
23501                    }
23502                }
23503                mKeepUninstalledPackages = new ArrayList<>(packageList);
23504                if (removedFromList != null) {
23505                    final int removedCount = removedFromList.size();
23506                    for (int i = 0; i < removedCount; i++) {
23507                        deletePackageIfUnusedLPr(removedFromList.get(i));
23508                    }
23509                }
23510            }
23511        }
23512
23513        @Override
23514        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23515            synchronized (mPackages) {
23516                return mPermissionManager.isPermissionsReviewRequired(
23517                        mPackages.get(packageName), userId);
23518            }
23519        }
23520
23521        @Override
23522        public PackageInfo getPackageInfo(
23523                String packageName, int flags, int filterCallingUid, int userId) {
23524            return PackageManagerService.this
23525                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23526                            flags, filterCallingUid, userId);
23527        }
23528
23529        @Override
23530        public int getPackageUid(String packageName, int flags, int userId) {
23531            return PackageManagerService.this
23532                    .getPackageUid(packageName, flags, userId);
23533        }
23534
23535        @Override
23536        public ApplicationInfo getApplicationInfo(
23537                String packageName, int flags, int filterCallingUid, int userId) {
23538            return PackageManagerService.this
23539                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23540        }
23541
23542        @Override
23543        public ActivityInfo getActivityInfo(
23544                ComponentName component, int flags, int filterCallingUid, int userId) {
23545            return PackageManagerService.this
23546                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23547        }
23548
23549        @Override
23550        public List<ResolveInfo> queryIntentActivities(
23551                Intent intent, int flags, int filterCallingUid, int userId) {
23552            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23553            return PackageManagerService.this
23554                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23555                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23556        }
23557
23558        @Override
23559        public List<ResolveInfo> queryIntentServices(
23560                Intent intent, int flags, int callingUid, int userId) {
23561            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23562            return PackageManagerService.this
23563                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23564                            false);
23565        }
23566
23567        @Override
23568        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23569                int userId) {
23570            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23571        }
23572
23573        @Override
23574        public ComponentName getDefaultHomeActivity(int userId) {
23575            return PackageManagerService.this.getDefaultHomeActivity(userId);
23576        }
23577
23578        @Override
23579        public void setDeviceAndProfileOwnerPackages(
23580                int deviceOwnerUserId, String deviceOwnerPackage,
23581                SparseArray<String> profileOwnerPackages) {
23582            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23583                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23584        }
23585
23586        @Override
23587        public boolean isPackageDataProtected(int userId, String packageName) {
23588            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23589        }
23590
23591        @Override
23592        public boolean isPackageEphemeral(int userId, String packageName) {
23593            synchronized (mPackages) {
23594                final PackageSetting ps = mSettings.mPackages.get(packageName);
23595                return ps != null ? ps.getInstantApp(userId) : false;
23596            }
23597        }
23598
23599        @Override
23600        public boolean wasPackageEverLaunched(String packageName, int userId) {
23601            synchronized (mPackages) {
23602                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23603            }
23604        }
23605
23606        @Override
23607        public void grantRuntimePermission(String packageName, String permName, int userId,
23608                boolean overridePolicy) {
23609            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23610                    permName, packageName, overridePolicy, getCallingUid(), userId,
23611                    mPermissionCallback);
23612        }
23613
23614        @Override
23615        public void revokeRuntimePermission(String packageName, String permName, int userId,
23616                boolean overridePolicy) {
23617            mPermissionManager.revokeRuntimePermission(
23618                    permName, packageName, overridePolicy, getCallingUid(), userId,
23619                    mPermissionCallback);
23620        }
23621
23622        @Override
23623        public String getNameForUid(int uid) {
23624            return PackageManagerService.this.getNameForUid(uid);
23625        }
23626
23627        @Override
23628        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23629                Intent origIntent, String resolvedType, String callingPackage,
23630                Bundle verificationBundle, int userId) {
23631            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23632                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23633                    userId);
23634        }
23635
23636        @Override
23637        public void grantEphemeralAccess(int userId, Intent intent,
23638                int targetAppId, int ephemeralAppId) {
23639            synchronized (mPackages) {
23640                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23641                        targetAppId, ephemeralAppId);
23642            }
23643        }
23644
23645        @Override
23646        public boolean isInstantAppInstallerComponent(ComponentName component) {
23647            synchronized (mPackages) {
23648                return mInstantAppInstallerActivity != null
23649                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23650            }
23651        }
23652
23653        @Override
23654        public void pruneInstantApps() {
23655            mInstantAppRegistry.pruneInstantApps();
23656        }
23657
23658        @Override
23659        public String getSetupWizardPackageName() {
23660            return mSetupWizardPackage;
23661        }
23662
23663        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23664            if (policy != null) {
23665                mExternalSourcesPolicy = policy;
23666            }
23667        }
23668
23669        @Override
23670        public boolean isPackagePersistent(String packageName) {
23671            synchronized (mPackages) {
23672                PackageParser.Package pkg = mPackages.get(packageName);
23673                return pkg != null
23674                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23675                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23676                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23677                        : false;
23678            }
23679        }
23680
23681        @Override
23682        public boolean isLegacySystemApp(Package pkg) {
23683            synchronized (mPackages) {
23684                final PackageSetting ps = (PackageSetting) pkg.mExtras;
23685                return mPromoteSystemApps
23686                        && ps.isSystem()
23687                        && mExistingSystemPackages.contains(ps.name);
23688            }
23689        }
23690
23691        @Override
23692        public List<PackageInfo> getOverlayPackages(int userId) {
23693            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23694            synchronized (mPackages) {
23695                for (PackageParser.Package p : mPackages.values()) {
23696                    if (p.mOverlayTarget != null) {
23697                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23698                        if (pkg != null) {
23699                            overlayPackages.add(pkg);
23700                        }
23701                    }
23702                }
23703            }
23704            return overlayPackages;
23705        }
23706
23707        @Override
23708        public List<String> getTargetPackageNames(int userId) {
23709            List<String> targetPackages = new ArrayList<>();
23710            synchronized (mPackages) {
23711                for (PackageParser.Package p : mPackages.values()) {
23712                    if (p.mOverlayTarget == null) {
23713                        targetPackages.add(p.packageName);
23714                    }
23715                }
23716            }
23717            return targetPackages;
23718        }
23719
23720        @Override
23721        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23722                @Nullable List<String> overlayPackageNames) {
23723            synchronized (mPackages) {
23724                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23725                    Slog.e(TAG, "failed to find package " + targetPackageName);
23726                    return false;
23727                }
23728                ArrayList<String> overlayPaths = null;
23729                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
23730                    final int N = overlayPackageNames.size();
23731                    overlayPaths = new ArrayList<>(N);
23732                    for (int i = 0; i < N; i++) {
23733                        final String packageName = overlayPackageNames.get(i);
23734                        final PackageParser.Package pkg = mPackages.get(packageName);
23735                        if (pkg == null) {
23736                            Slog.e(TAG, "failed to find package " + packageName);
23737                            return false;
23738                        }
23739                        overlayPaths.add(pkg.baseCodePath);
23740                    }
23741                }
23742
23743                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
23744                ps.setOverlayPaths(overlayPaths, userId);
23745                return true;
23746            }
23747        }
23748
23749        @Override
23750        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23751                int flags, int userId, boolean resolveForStart) {
23752            return resolveIntentInternal(
23753                    intent, resolvedType, flags, userId, resolveForStart);
23754        }
23755
23756        @Override
23757        public ResolveInfo resolveService(Intent intent, String resolvedType,
23758                int flags, int userId, int callingUid) {
23759            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23760        }
23761
23762        @Override
23763        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
23764            return PackageManagerService.this.resolveContentProviderInternal(
23765                    name, flags, userId);
23766        }
23767
23768        @Override
23769        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23770            synchronized (mPackages) {
23771                mIsolatedOwners.put(isolatedUid, ownerUid);
23772            }
23773        }
23774
23775        @Override
23776        public void removeIsolatedUid(int isolatedUid) {
23777            synchronized (mPackages) {
23778                mIsolatedOwners.delete(isolatedUid);
23779            }
23780        }
23781
23782        @Override
23783        public int getUidTargetSdkVersion(int uid) {
23784            synchronized (mPackages) {
23785                return getUidTargetSdkVersionLockedLPr(uid);
23786            }
23787        }
23788
23789        @Override
23790        public int getPackageTargetSdkVersion(String packageName) {
23791            synchronized (mPackages) {
23792                return getPackageTargetSdkVersionLockedLPr(packageName);
23793            }
23794        }
23795
23796        @Override
23797        public boolean canAccessInstantApps(int callingUid, int userId) {
23798            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
23799        }
23800
23801        @Override
23802        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
23803            synchronized (mPackages) {
23804                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
23805            }
23806        }
23807
23808        @Override
23809        public void notifyPackageUse(String packageName, int reason) {
23810            synchronized (mPackages) {
23811                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
23812            }
23813        }
23814    }
23815
23816    @Override
23817    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23818        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23819        synchronized (mPackages) {
23820            final long identity = Binder.clearCallingIdentity();
23821            try {
23822                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
23823                        packageNames, userId);
23824            } finally {
23825                Binder.restoreCallingIdentity(identity);
23826            }
23827        }
23828    }
23829
23830    @Override
23831    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23832        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23833        synchronized (mPackages) {
23834            final long identity = Binder.clearCallingIdentity();
23835            try {
23836                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
23837                        packageNames, userId);
23838            } finally {
23839                Binder.restoreCallingIdentity(identity);
23840            }
23841        }
23842    }
23843
23844    private static void enforceSystemOrPhoneCaller(String tag) {
23845        int callingUid = Binder.getCallingUid();
23846        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23847            throw new SecurityException(
23848                    "Cannot call " + tag + " from UID " + callingUid);
23849        }
23850    }
23851
23852    boolean isHistoricalPackageUsageAvailable() {
23853        return mPackageUsage.isHistoricalPackageUsageAvailable();
23854    }
23855
23856    /**
23857     * Return a <b>copy</b> of the collection of packages known to the package manager.
23858     * @return A copy of the values of mPackages.
23859     */
23860    Collection<PackageParser.Package> getPackages() {
23861        synchronized (mPackages) {
23862            return new ArrayList<>(mPackages.values());
23863        }
23864    }
23865
23866    /**
23867     * Logs process start information (including base APK hash) to the security log.
23868     * @hide
23869     */
23870    @Override
23871    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23872            String apkFile, int pid) {
23873        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23874            return;
23875        }
23876        if (!SecurityLog.isLoggingEnabled()) {
23877            return;
23878        }
23879        Bundle data = new Bundle();
23880        data.putLong("startTimestamp", System.currentTimeMillis());
23881        data.putString("processName", processName);
23882        data.putInt("uid", uid);
23883        data.putString("seinfo", seinfo);
23884        data.putString("apkFile", apkFile);
23885        data.putInt("pid", pid);
23886        Message msg = mProcessLoggingHandler.obtainMessage(
23887                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23888        msg.setData(data);
23889        mProcessLoggingHandler.sendMessage(msg);
23890    }
23891
23892    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23893        return mCompilerStats.getPackageStats(pkgName);
23894    }
23895
23896    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23897        return getOrCreateCompilerPackageStats(pkg.packageName);
23898    }
23899
23900    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23901        return mCompilerStats.getOrCreatePackageStats(pkgName);
23902    }
23903
23904    public void deleteCompilerPackageStats(String pkgName) {
23905        mCompilerStats.deletePackageStats(pkgName);
23906    }
23907
23908    @Override
23909    public int getInstallReason(String packageName, int userId) {
23910        final int callingUid = Binder.getCallingUid();
23911        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
23912                true /* requireFullPermission */, false /* checkShell */,
23913                "get install reason");
23914        synchronized (mPackages) {
23915            final PackageSetting ps = mSettings.mPackages.get(packageName);
23916            if (filterAppAccessLPr(ps, callingUid, userId)) {
23917                return PackageManager.INSTALL_REASON_UNKNOWN;
23918            }
23919            if (ps != null) {
23920                return ps.getInstallReason(userId);
23921            }
23922        }
23923        return PackageManager.INSTALL_REASON_UNKNOWN;
23924    }
23925
23926    @Override
23927    public boolean canRequestPackageInstalls(String packageName, int userId) {
23928        return canRequestPackageInstallsInternal(packageName, 0, userId,
23929                true /* throwIfPermNotDeclared*/);
23930    }
23931
23932    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
23933            boolean throwIfPermNotDeclared) {
23934        int callingUid = Binder.getCallingUid();
23935        int uid = getPackageUid(packageName, 0, userId);
23936        if (callingUid != uid && callingUid != Process.ROOT_UID
23937                && callingUid != Process.SYSTEM_UID) {
23938            throw new SecurityException(
23939                    "Caller uid " + callingUid + " does not own package " + packageName);
23940        }
23941        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
23942        if (info == null) {
23943            return false;
23944        }
23945        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23946            return false;
23947        }
23948        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23949        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23950        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23951            if (throwIfPermNotDeclared) {
23952                throw new SecurityException("Need to declare " + appOpPermission
23953                        + " to call this api");
23954            } else {
23955                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
23956                return false;
23957            }
23958        }
23959        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23960            return false;
23961        }
23962        if (mExternalSourcesPolicy != null) {
23963            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23964            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23965                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23966            }
23967        }
23968        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23969    }
23970
23971    @Override
23972    public ComponentName getInstantAppResolverSettingsComponent() {
23973        return mInstantAppResolverSettingsComponent;
23974    }
23975
23976    @Override
23977    public ComponentName getInstantAppInstallerComponent() {
23978        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23979            return null;
23980        }
23981        return mInstantAppInstallerActivity == null
23982                ? null : mInstantAppInstallerActivity.getComponentName();
23983    }
23984
23985    @Override
23986    public String getInstantAppAndroidId(String packageName, int userId) {
23987        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
23988                "getInstantAppAndroidId");
23989        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
23990                true /* requireFullPermission */, false /* checkShell */,
23991                "getInstantAppAndroidId");
23992        // Make sure the target is an Instant App.
23993        if (!isInstantApp(packageName, userId)) {
23994            return null;
23995        }
23996        synchronized (mPackages) {
23997            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
23998        }
23999    }
24000
24001    boolean canHaveOatDir(String packageName) {
24002        synchronized (mPackages) {
24003            PackageParser.Package p = mPackages.get(packageName);
24004            if (p == null) {
24005                return false;
24006            }
24007            return p.canHaveOatDir();
24008        }
24009    }
24010
24011    private String getOatDir(PackageParser.Package pkg) {
24012        if (!pkg.canHaveOatDir()) {
24013            return null;
24014        }
24015        File codePath = new File(pkg.codePath);
24016        if (codePath.isDirectory()) {
24017            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
24018        }
24019        return null;
24020    }
24021
24022    void deleteOatArtifactsOfPackage(String packageName) {
24023        final String[] instructionSets;
24024        final List<String> codePaths;
24025        final String oatDir;
24026        final PackageParser.Package pkg;
24027        synchronized (mPackages) {
24028            pkg = mPackages.get(packageName);
24029        }
24030        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24031        codePaths = pkg.getAllCodePaths();
24032        oatDir = getOatDir(pkg);
24033
24034        for (String codePath : codePaths) {
24035            for (String isa : instructionSets) {
24036                try {
24037                    mInstaller.deleteOdex(codePath, isa, oatDir);
24038                } catch (InstallerException e) {
24039                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24040                }
24041            }
24042        }
24043    }
24044
24045    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24046        Set<String> unusedPackages = new HashSet<>();
24047        long currentTimeInMillis = System.currentTimeMillis();
24048        synchronized (mPackages) {
24049            for (PackageParser.Package pkg : mPackages.values()) {
24050                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24051                if (ps == null) {
24052                    continue;
24053                }
24054                PackageDexUsage.PackageUseInfo packageUseInfo =
24055                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24056                if (PackageManagerServiceUtils
24057                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24058                                downgradeTimeThresholdMillis, packageUseInfo,
24059                                pkg.getLatestPackageUseTimeInMills(),
24060                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24061                    unusedPackages.add(pkg.packageName);
24062                }
24063            }
24064        }
24065        return unusedPackages;
24066    }
24067
24068    @Override
24069    public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
24070            int userId) {
24071        final int callingUid = Binder.getCallingUid();
24072        final int callingAppId = UserHandle.getAppId(callingUid);
24073
24074        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24075                true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
24076
24077        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24078                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24079            throw new SecurityException("Caller must have the "
24080                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24081        }
24082
24083        synchronized(mPackages) {
24084            mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
24085            scheduleWritePackageRestrictionsLocked(userId);
24086        }
24087    }
24088
24089    @Nullable
24090    @Override
24091    public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
24092        final int callingUid = Binder.getCallingUid();
24093        final int callingAppId = UserHandle.getAppId(callingUid);
24094
24095        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24096                true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
24097
24098        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24099                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24100            throw new SecurityException("Caller must have the "
24101                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24102        }
24103
24104        synchronized(mPackages) {
24105            return mSettings.getHarmfulAppWarningLPr(packageName, userId);
24106        }
24107    }
24108}
24109
24110interface PackageSender {
24111    /**
24112     * @param userIds User IDs where the action occurred on a full application
24113     * @param instantUserIds User IDs where the action occurred on an instant application
24114     */
24115    void sendPackageBroadcast(final String action, final String pkg,
24116        final Bundle extras, final int flags, final String targetPkg,
24117        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
24118    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24119        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
24120    void notifyPackageAdded(String packageName);
24121    void notifyPackageRemoved(String packageName);
24122}
24123