PackageManagerService.java revision dc0dd242871bf95b574676c0a7434849cd80a699
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.INSTALL_PACKAGES;
21import static android.Manifest.permission.MANAGE_DEVICE_ADMINS;
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.SET_HARMFUL_APP_WARNINGS;
26import static android.Manifest.permission.WRITE_EXTERNAL_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;
91
92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
93import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
94import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
95import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
96import static com.android.internal.util.ArrayUtils.appendInt;
97import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
99import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
100import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
101import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
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.annotation.UserIdInt;
121import android.app.ActivityManager;
122import android.app.ActivityManagerInternal;
123import android.app.AppOpsManager;
124import android.app.IActivityManager;
125import android.app.ResourcesManager;
126import android.app.admin.IDevicePolicyManager;
127import android.app.admin.SecurityLog;
128import android.app.backup.IBackupManager;
129import android.content.BroadcastReceiver;
130import android.content.ComponentName;
131import android.content.ContentResolver;
132import android.content.Context;
133import android.content.IIntentReceiver;
134import android.content.Intent;
135import android.content.IntentFilter;
136import android.content.IntentSender;
137import android.content.IntentSender.SendIntentException;
138import android.content.ServiceConnection;
139import android.content.pm.ActivityInfo;
140import android.content.pm.ApplicationInfo;
141import android.content.pm.AppsQueryHelper;
142import android.content.pm.AuxiliaryResolveInfo;
143import android.content.pm.ChangedPackages;
144import android.content.pm.ComponentInfo;
145import android.content.pm.FallbackCategoryProvider;
146import android.content.pm.FeatureInfo;
147import android.content.pm.IDexModuleRegisterCallback;
148import android.content.pm.IOnPermissionsChangeListener;
149import android.content.pm.IPackageDataObserver;
150import android.content.pm.IPackageDeleteObserver;
151import android.content.pm.IPackageDeleteObserver2;
152import android.content.pm.IPackageInstallObserver2;
153import android.content.pm.IPackageInstaller;
154import android.content.pm.IPackageManager;
155import android.content.pm.IPackageManagerNative;
156import android.content.pm.IPackageMoveObserver;
157import android.content.pm.IPackageStatsObserver;
158import android.content.pm.InstantAppInfo;
159import android.content.pm.InstantAppRequest;
160import android.content.pm.InstantAppResolveInfo;
161import android.content.pm.InstrumentationInfo;
162import android.content.pm.IntentFilterVerificationInfo;
163import android.content.pm.KeySet;
164import android.content.pm.PackageCleanItem;
165import android.content.pm.PackageInfo;
166import android.content.pm.PackageInfoLite;
167import android.content.pm.PackageInstaller;
168import android.content.pm.PackageList;
169import android.content.pm.PackageManager;
170import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
171import android.content.pm.PackageManagerInternal;
172import android.content.pm.PackageManagerInternal.PackageListObserver;
173import android.content.pm.PackageParser;
174import android.content.pm.PackageParser.ActivityIntentInfo;
175import android.content.pm.PackageParser.Package;
176import android.content.pm.PackageParser.PackageLite;
177import android.content.pm.PackageParser.PackageParserException;
178import android.content.pm.PackageParser.ParseFlags;
179import android.content.pm.PackageParser.ServiceIntentInfo;
180import android.content.pm.PackageParser.SigningDetails;
181import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion;
182import android.content.pm.PackageStats;
183import android.content.pm.PackageUserState;
184import android.content.pm.ParceledListSlice;
185import android.content.pm.PermissionGroupInfo;
186import android.content.pm.PermissionInfo;
187import android.content.pm.ProviderInfo;
188import android.content.pm.ResolveInfo;
189import android.content.pm.SELinuxUtil;
190import android.content.pm.ServiceInfo;
191import android.content.pm.SharedLibraryInfo;
192import android.content.pm.Signature;
193import android.content.pm.UserInfo;
194import android.content.pm.VerifierDeviceIdentity;
195import android.content.pm.VerifierInfo;
196import android.content.pm.VersionedPackage;
197import android.content.pm.dex.ArtManager;
198import android.content.pm.dex.DexMetadataHelper;
199import android.content.pm.dex.IArtManager;
200import android.content.res.Resources;
201import android.database.ContentObserver;
202import android.graphics.Bitmap;
203import android.hardware.display.DisplayManager;
204import android.net.Uri;
205import android.os.AsyncTask;
206import android.os.Binder;
207import android.os.Build;
208import android.os.Bundle;
209import android.os.Debug;
210import android.os.Environment;
211import android.os.Environment.UserEnvironment;
212import android.os.FileUtils;
213import android.os.Handler;
214import android.os.IBinder;
215import android.os.Looper;
216import android.os.Message;
217import android.os.Parcel;
218import android.os.ParcelFileDescriptor;
219import android.os.PatternMatcher;
220import android.os.PersistableBundle;
221import android.os.Process;
222import android.os.RemoteCallbackList;
223import android.os.RemoteException;
224import android.os.ResultReceiver;
225import android.os.SELinux;
226import android.os.ServiceManager;
227import android.os.ShellCallback;
228import android.os.SystemClock;
229import android.os.SystemProperties;
230import android.os.Trace;
231import android.os.UserHandle;
232import android.os.UserManager;
233import android.os.UserManagerInternal;
234import android.os.storage.IStorageManager;
235import android.os.storage.StorageEventListener;
236import android.os.storage.StorageManager;
237import android.os.storage.StorageManagerInternal;
238import android.os.storage.VolumeInfo;
239import android.os.storage.VolumeRecord;
240import android.provider.Settings.Global;
241import android.provider.Settings.Secure;
242import android.security.KeyStore;
243import android.security.SystemKeyStore;
244import android.service.pm.PackageServiceDumpProto;
245import android.system.ErrnoException;
246import android.system.Os;
247import android.text.TextUtils;
248import android.text.format.DateUtils;
249import android.util.ArrayMap;
250import android.util.ArraySet;
251import android.util.Base64;
252import android.util.ByteStringUtils;
253import android.util.DisplayMetrics;
254import android.util.EventLog;
255import android.util.ExceptionUtils;
256import android.util.Log;
257import android.util.LogPrinter;
258import android.util.LongSparseArray;
259import android.util.LongSparseLongArray;
260import android.util.MathUtils;
261import android.util.PackageUtils;
262import android.util.Pair;
263import android.util.PrintStreamPrinter;
264import android.util.Slog;
265import android.util.SparseArray;
266import android.util.SparseBooleanArray;
267import android.util.SparseIntArray;
268import android.util.TimingsTraceLog;
269import android.util.Xml;
270import android.util.jar.StrictJarFile;
271import android.util.proto.ProtoOutputStream;
272import android.view.Display;
273
274import com.android.internal.R;
275import com.android.internal.annotations.GuardedBy;
276import com.android.internal.app.IMediaContainerService;
277import com.android.internal.app.ResolverActivity;
278import com.android.internal.content.NativeLibraryHelper;
279import com.android.internal.content.PackageHelper;
280import com.android.internal.logging.MetricsLogger;
281import com.android.internal.os.IParcelFileDescriptorFactory;
282import com.android.internal.os.SomeArgs;
283import com.android.internal.os.Zygote;
284import com.android.internal.telephony.CarrierAppUtils;
285import com.android.internal.util.ArrayUtils;
286import com.android.internal.util.ConcurrentUtils;
287import com.android.internal.util.DumpUtils;
288import com.android.internal.util.FastXmlSerializer;
289import com.android.internal.util.IndentingPrintWriter;
290import com.android.internal.util.Preconditions;
291import com.android.internal.util.XmlUtils;
292import com.android.server.AttributeCache;
293import com.android.server.DeviceIdleController;
294import com.android.server.EventLogTags;
295import com.android.server.FgThread;
296import com.android.server.IntentResolver;
297import com.android.server.LocalServices;
298import com.android.server.LockGuard;
299import com.android.server.ServiceThread;
300import com.android.server.SystemConfig;
301import com.android.server.SystemServerInitThreadPool;
302import com.android.server.Watchdog;
303import com.android.server.net.NetworkPolicyManagerInternal;
304import com.android.server.pm.Installer.InstallerException;
305import com.android.server.pm.Settings.DatabaseVersion;
306import com.android.server.pm.Settings.VersionInfo;
307import com.android.server.pm.dex.ArtManagerService;
308import com.android.server.pm.dex.DexLogger;
309import com.android.server.pm.dex.DexManager;
310import com.android.server.pm.dex.DexoptOptions;
311import com.android.server.pm.dex.PackageDexUsage;
312import com.android.server.pm.permission.BasePermission;
313import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
314import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
315import com.android.server.pm.permission.PermissionManagerInternal;
316import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
317import com.android.server.pm.permission.PermissionManagerService;
318import com.android.server.pm.permission.PermissionsState;
319import com.android.server.pm.permission.PermissionsState.PermissionState;
320import com.android.server.security.VerityUtils;
321import com.android.server.storage.DeviceStorageMonitorInternal;
322
323import dalvik.system.CloseGuard;
324import dalvik.system.VMRuntime;
325
326import libcore.io.IoUtils;
327
328import org.xmlpull.v1.XmlPullParser;
329import org.xmlpull.v1.XmlPullParserException;
330import org.xmlpull.v1.XmlSerializer;
331
332import java.io.BufferedOutputStream;
333import java.io.ByteArrayInputStream;
334import java.io.ByteArrayOutputStream;
335import java.io.File;
336import java.io.FileDescriptor;
337import java.io.FileInputStream;
338import java.io.FileOutputStream;
339import java.io.FilenameFilter;
340import java.io.IOException;
341import java.io.PrintWriter;
342import java.lang.annotation.Retention;
343import java.lang.annotation.RetentionPolicy;
344import java.nio.charset.StandardCharsets;
345import java.security.DigestException;
346import java.security.DigestInputStream;
347import java.security.MessageDigest;
348import java.security.NoSuchAlgorithmException;
349import java.security.PublicKey;
350import java.security.SecureRandom;
351import java.security.cert.CertificateException;
352import java.util.ArrayList;
353import java.util.Arrays;
354import java.util.Collection;
355import java.util.Collections;
356import java.util.Comparator;
357import java.util.HashMap;
358import java.util.HashSet;
359import java.util.Iterator;
360import java.util.LinkedHashSet;
361import java.util.List;
362import java.util.Map;
363import java.util.Objects;
364import java.util.Set;
365import java.util.concurrent.CountDownLatch;
366import java.util.concurrent.Future;
367import java.util.concurrent.TimeUnit;
368import java.util.concurrent.atomic.AtomicBoolean;
369import java.util.concurrent.atomic.AtomicInteger;
370import java.util.function.Predicate;
371
372/**
373 * Keep track of all those APKs everywhere.
374 * <p>
375 * Internally there are two important locks:
376 * <ul>
377 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
378 * and other related state. It is a fine-grained lock that should only be held
379 * momentarily, as it's one of the most contended locks in the system.
380 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
381 * operations typically involve heavy lifting of application data on disk. Since
382 * {@code installd} is single-threaded, and it's operations can often be slow,
383 * this lock should never be acquired while already holding {@link #mPackages}.
384 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
385 * holding {@link #mInstallLock}.
386 * </ul>
387 * Many internal methods rely on the caller to hold the appropriate locks, and
388 * this contract is expressed through method name suffixes:
389 * <ul>
390 * <li>fooLI(): the caller must hold {@link #mInstallLock}
391 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
392 * being modified must be frozen
393 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
394 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
395 * </ul>
396 * <p>
397 * Because this class is very central to the platform's security; please run all
398 * CTS and unit tests whenever making modifications:
399 *
400 * <pre>
401 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
402 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
403 * </pre>
404 */
405public class PackageManagerService extends IPackageManager.Stub
406        implements PackageSender {
407    static final String TAG = "PackageManager";
408    public static final boolean DEBUG_SETTINGS = false;
409    static final boolean DEBUG_PREFERRED = false;
410    static final boolean DEBUG_UPGRADE = false;
411    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
412    private static final boolean DEBUG_BACKUP = false;
413    public static final boolean DEBUG_INSTALL = false;
414    public static final boolean DEBUG_REMOVE = false;
415    private static final boolean DEBUG_BROADCASTS = false;
416    private static final boolean DEBUG_SHOW_INFO = false;
417    private static final boolean DEBUG_PACKAGE_INFO = false;
418    private static final boolean DEBUG_INTENT_MATCHING = false;
419    public static final boolean DEBUG_PACKAGE_SCANNING = false;
420    private static final boolean DEBUG_VERIFY = false;
421    private static final boolean DEBUG_FILTERS = false;
422    public static final boolean DEBUG_PERMISSIONS = false;
423    private static final boolean DEBUG_SHARED_LIBRARIES = false;
424    public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
425
426    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
427    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
428    // user, but by default initialize to this.
429    public static final boolean DEBUG_DEXOPT = false;
430
431    private static final boolean DEBUG_ABI_SELECTION = false;
432    private static final boolean DEBUG_INSTANT = Build.IS_DEBUGGABLE;
433    private static final boolean DEBUG_TRIAGED_MISSING = false;
434    private static final boolean DEBUG_APP_DATA = false;
435
436    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
437    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
438
439    private static final boolean HIDE_EPHEMERAL_APIS = false;
440
441    private static final boolean ENABLE_FREE_CACHE_V2 =
442            SystemProperties.getBoolean("fw.free_cache_v2", true);
443
444    private static final int RADIO_UID = Process.PHONE_UID;
445    private static final int LOG_UID = Process.LOG_UID;
446    private static final int NFC_UID = Process.NFC_UID;
447    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
448    private static final int SHELL_UID = Process.SHELL_UID;
449    private static final int SE_UID = Process.SE_UID;
450
451    // Suffix used during package installation when copying/moving
452    // package apks to install directory.
453    private static final String INSTALL_PACKAGE_SUFFIX = "-";
454
455    static final int SCAN_NO_DEX = 1<<0;
456    static final int SCAN_UPDATE_SIGNATURE = 1<<1;
457    static final int SCAN_NEW_INSTALL = 1<<2;
458    static final int SCAN_UPDATE_TIME = 1<<3;
459    static final int SCAN_BOOTING = 1<<4;
460    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6;
461    static final int SCAN_REQUIRE_KNOWN = 1<<7;
462    static final int SCAN_MOVE = 1<<8;
463    static final int SCAN_INITIAL = 1<<9;
464    static final int SCAN_CHECK_ONLY = 1<<10;
465    static final int SCAN_DONT_KILL_APP = 1<<11;
466    static final int SCAN_IGNORE_FROZEN = 1<<12;
467    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13;
468    static final int SCAN_AS_INSTANT_APP = 1<<14;
469    static final int SCAN_AS_FULL_APP = 1<<15;
470    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16;
471    static final int SCAN_AS_SYSTEM = 1<<17;
472    static final int SCAN_AS_PRIVILEGED = 1<<18;
473    static final int SCAN_AS_OEM = 1<<19;
474    static final int SCAN_AS_VENDOR = 1<<20;
475    static final int SCAN_AS_PRODUCT = 1<<21;
476
477    @IntDef(flag = true, prefix = { "SCAN_" }, value = {
478            SCAN_NO_DEX,
479            SCAN_UPDATE_SIGNATURE,
480            SCAN_NEW_INSTALL,
481            SCAN_UPDATE_TIME,
482            SCAN_BOOTING,
483            SCAN_DELETE_DATA_ON_FAILURES,
484            SCAN_REQUIRE_KNOWN,
485            SCAN_MOVE,
486            SCAN_INITIAL,
487            SCAN_CHECK_ONLY,
488            SCAN_DONT_KILL_APP,
489            SCAN_IGNORE_FROZEN,
490            SCAN_FIRST_BOOT_OR_UPGRADE,
491            SCAN_AS_INSTANT_APP,
492            SCAN_AS_FULL_APP,
493            SCAN_AS_VIRTUAL_PRELOAD,
494    })
495    @Retention(RetentionPolicy.SOURCE)
496    public @interface ScanFlags {}
497
498    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
499    /** Extension of the compressed packages */
500    public final static String COMPRESSED_EXTENSION = ".gz";
501    /** Suffix of stub packages on the system partition */
502    public final static String STUB_SUFFIX = "-Stub";
503
504    private static final int[] EMPTY_INT_ARRAY = new int[0];
505
506    private static final int TYPE_UNKNOWN = 0;
507    private static final int TYPE_ACTIVITY = 1;
508    private static final int TYPE_RECEIVER = 2;
509    private static final int TYPE_SERVICE = 3;
510    private static final int TYPE_PROVIDER = 4;
511    @IntDef(prefix = { "TYPE_" }, value = {
512            TYPE_UNKNOWN,
513            TYPE_ACTIVITY,
514            TYPE_RECEIVER,
515            TYPE_SERVICE,
516            TYPE_PROVIDER,
517    })
518    @Retention(RetentionPolicy.SOURCE)
519    public @interface ComponentType {}
520
521    /**
522     * Timeout (in milliseconds) after which the watchdog should declare that
523     * our handler thread is wedged.  The usual default for such things is one
524     * minute but we sometimes do very lengthy I/O operations on this thread,
525     * such as installing multi-gigabyte applications, so ours needs to be longer.
526     */
527    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
528
529    /**
530     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
531     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
532     * settings entry if available, otherwise we use the hardcoded default.  If it's been
533     * more than this long since the last fstrim, we force one during the boot sequence.
534     *
535     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
536     * one gets run at the next available charging+idle time.  This final mandatory
537     * no-fstrim check kicks in only of the other scheduling criteria is never met.
538     */
539    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
540
541    /**
542     * Whether verification is enabled by default.
543     */
544    private static final boolean DEFAULT_VERIFY_ENABLE = true;
545
546    /**
547     * The default maximum time to wait for the verification agent to return in
548     * milliseconds.
549     */
550    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
551
552    /**
553     * The default response for package verification timeout.
554     *
555     * This can be either PackageManager.VERIFICATION_ALLOW or
556     * PackageManager.VERIFICATION_REJECT.
557     */
558    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
559
560    public static final String PLATFORM_PACKAGE_NAME = "android";
561
562    public static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
563
564    public static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
565            DEFAULT_CONTAINER_PACKAGE,
566            "com.android.defcontainer.DefaultContainerService");
567
568    private static final String KILL_APP_REASON_GIDS_CHANGED =
569            "permission grant or revoke changed gids";
570
571    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
572            "permissions revoked";
573
574    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
575
576    private static final String PACKAGE_SCHEME = "package";
577
578    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
579
580    private static final String PRODUCT_OVERLAY_DIR = "/product/overlay";
581
582    /** Canonical intent used to identify what counts as a "web browser" app */
583    private static final Intent sBrowserIntent;
584    static {
585        sBrowserIntent = new Intent();
586        sBrowserIntent.setAction(Intent.ACTION_VIEW);
587        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
588        sBrowserIntent.setData(Uri.parse("http:"));
589        sBrowserIntent.addFlags(Intent.FLAG_IGNORE_EPHEMERAL);
590    }
591
592    /**
593     * The set of all protected actions [i.e. those actions for which a high priority
594     * intent filter is disallowed].
595     */
596    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
597    static {
598        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
599        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
600        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
601        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
602    }
603
604    // Compilation reasons.
605    public static final int REASON_UNKNOWN = -1;
606    public static final int REASON_FIRST_BOOT = 0;
607    public static final int REASON_BOOT = 1;
608    public static final int REASON_INSTALL = 2;
609    public static final int REASON_BACKGROUND_DEXOPT = 3;
610    public static final int REASON_AB_OTA = 4;
611    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
612    public static final int REASON_SHARED = 6;
613
614    public static final int REASON_LAST = REASON_SHARED;
615
616    /**
617     * Version number for the package parser cache. Increment this whenever the format or
618     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
619     */
620    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
621
622    /**
623     * Whether the package parser cache is enabled.
624     */
625    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
626
627    /**
628     * Permissions required in order to receive instant application lifecycle broadcasts.
629     */
630    private static final String[] INSTANT_APP_BROADCAST_PERMISSION =
631            new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS };
632
633    final ServiceThread mHandlerThread;
634
635    final PackageHandler mHandler;
636
637    private final ProcessLoggingHandler mProcessLoggingHandler;
638
639    /**
640     * Messages for {@link #mHandler} that need to wait for system ready before
641     * being dispatched.
642     */
643    private ArrayList<Message> mPostSystemReadyMessages;
644
645    final int mSdkVersion = Build.VERSION.SDK_INT;
646
647    final Context mContext;
648    final boolean mFactoryTest;
649    final boolean mOnlyCore;
650    final DisplayMetrics mMetrics;
651    final int mDefParseFlags;
652    final String[] mSeparateProcesses;
653    final boolean mIsUpgrade;
654    final boolean mIsPreNUpgrade;
655    final boolean mIsPreNMR1Upgrade;
656
657    // Have we told the Activity Manager to whitelist the default container service by uid yet?
658    @GuardedBy("mPackages")
659    boolean mDefaultContainerWhitelisted = false;
660
661    @GuardedBy("mPackages")
662    private boolean mDexOptDialogShown;
663
664    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
665    // LOCK HELD.  Can be called with mInstallLock held.
666    @GuardedBy("mInstallLock")
667    final Installer mInstaller;
668
669    /** Directory where installed applications are stored */
670    private static final File sAppInstallDir =
671            new File(Environment.getDataDirectory(), "app");
672    /** Directory where installed application's 32-bit native libraries are copied. */
673    private static final File sAppLib32InstallDir =
674            new File(Environment.getDataDirectory(), "app-lib");
675    /** Directory where code and non-resource assets of forward-locked applications are stored */
676    private static final File sDrmAppPrivateInstallDir =
677            new File(Environment.getDataDirectory(), "app-private");
678
679    // ----------------------------------------------------------------
680
681    // Lock for state used when installing and doing other long running
682    // operations.  Methods that must be called with this lock held have
683    // the suffix "LI".
684    final Object mInstallLock = new Object();
685
686    // ----------------------------------------------------------------
687
688    // Keys are String (package name), values are Package.  This also serves
689    // as the lock for the global state.  Methods that must be called with
690    // this lock held have the prefix "LP".
691    @GuardedBy("mPackages")
692    final ArrayMap<String, PackageParser.Package> mPackages =
693            new ArrayMap<String, PackageParser.Package>();
694
695    final ArrayMap<String, Set<String>> mKnownCodebase =
696            new ArrayMap<String, Set<String>>();
697
698    // Keys are isolated uids and values are the uid of the application
699    // that created the isolated proccess.
700    @GuardedBy("mPackages")
701    final SparseIntArray mIsolatedOwners = new SparseIntArray();
702
703    /**
704     * Tracks new system packages [received in an OTA] that we expect to
705     * find updated user-installed versions. Keys are package name, values
706     * are package location.
707     */
708    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
709    /**
710     * Tracks high priority intent filters for protected actions. During boot, certain
711     * filter actions are protected and should never be allowed to have a high priority
712     * intent filter for them. However, there is one, and only one exception -- the
713     * setup wizard. It must be able to define a high priority intent filter for these
714     * actions to ensure there are no escapes from the wizard. We need to delay processing
715     * of these during boot as we need to look at all of the system packages in order
716     * to know which component is the setup wizard.
717     */
718    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
719    /**
720     * Whether or not processing protected filters should be deferred.
721     */
722    private boolean mDeferProtectedFilters = true;
723
724    /**
725     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
726     */
727    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
728    /**
729     * Whether or not system app permissions should be promoted from install to runtime.
730     */
731    boolean mPromoteSystemApps;
732
733    @GuardedBy("mPackages")
734    final Settings mSettings;
735
736    /**
737     * Set of package names that are currently "frozen", which means active
738     * surgery is being done on the code/data for that package. The platform
739     * will refuse to launch frozen packages to avoid race conditions.
740     *
741     * @see PackageFreezer
742     */
743    @GuardedBy("mPackages")
744    final ArraySet<String> mFrozenPackages = new ArraySet<>();
745
746    final ProtectedPackages mProtectedPackages;
747
748    @GuardedBy("mLoadedVolumes")
749    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
750
751    boolean mFirstBoot;
752
753    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
754
755    @GuardedBy("mAvailableFeatures")
756    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
757
758    private final InstantAppRegistry mInstantAppRegistry;
759
760    @GuardedBy("mPackages")
761    int mChangedPackagesSequenceNumber;
762    /**
763     * List of changed [installed, removed or updated] packages.
764     * mapping from user id -> sequence number -> package name
765     */
766    @GuardedBy("mPackages")
767    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
768    /**
769     * The sequence number of the last change to a package.
770     * mapping from user id -> package name -> sequence number
771     */
772    @GuardedBy("mPackages")
773    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
774
775    @GuardedBy("mPackages")
776    final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>();
777
778    class PackageParserCallback implements PackageParser.Callback {
779        @Override public final boolean hasFeature(String feature) {
780            return PackageManagerService.this.hasSystemFeature(feature, 0);
781        }
782
783        final List<PackageParser.Package> getStaticOverlayPackages(
784                Collection<PackageParser.Package> allPackages, String targetPackageName) {
785            if ("android".equals(targetPackageName)) {
786                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
787                // native AssetManager.
788                return null;
789            }
790
791            List<PackageParser.Package> overlayPackages = null;
792            for (PackageParser.Package p : allPackages) {
793                if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) {
794                    if (overlayPackages == null) {
795                        overlayPackages = new ArrayList<PackageParser.Package>();
796                    }
797                    overlayPackages.add(p);
798                }
799            }
800            if (overlayPackages != null) {
801                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
802                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
803                        return p1.mOverlayPriority - p2.mOverlayPriority;
804                    }
805                };
806                Collections.sort(overlayPackages, cmp);
807            }
808            return overlayPackages;
809        }
810
811        final String[] getStaticOverlayPaths(List<PackageParser.Package> overlayPackages,
812                String targetPath) {
813            if (overlayPackages == null || overlayPackages.isEmpty()) {
814                return null;
815            }
816            List<String> overlayPathList = null;
817            for (PackageParser.Package overlayPackage : overlayPackages) {
818                if (targetPath == null) {
819                    if (overlayPathList == null) {
820                        overlayPathList = new ArrayList<String>();
821                    }
822                    overlayPathList.add(overlayPackage.baseCodePath);
823                    continue;
824                }
825
826                try {
827                    // Creates idmaps for system to parse correctly the Android manifest of the
828                    // target package.
829                    //
830                    // OverlayManagerService will update each of them with a correct gid from its
831                    // target package app id.
832                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
833                            UserHandle.getSharedAppGid(
834                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
835                    if (overlayPathList == null) {
836                        overlayPathList = new ArrayList<String>();
837                    }
838                    overlayPathList.add(overlayPackage.baseCodePath);
839                } catch (InstallerException e) {
840                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
841                            overlayPackage.baseCodePath);
842                }
843            }
844            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
845        }
846
847        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
848            List<PackageParser.Package> overlayPackages;
849            synchronized (mInstallLock) {
850                synchronized (mPackages) {
851                    overlayPackages = getStaticOverlayPackages(
852                            mPackages.values(), targetPackageName);
853                }
854                // It is safe to keep overlayPackages without holding mPackages because static overlay
855                // packages can't be uninstalled or disabled.
856                return getStaticOverlayPaths(overlayPackages, targetPath);
857            }
858        }
859
860        @Override public final String[] getOverlayApks(String targetPackageName) {
861            return getStaticOverlayPaths(targetPackageName, null);
862        }
863
864        @Override public final String[] getOverlayPaths(String targetPackageName,
865                String targetPath) {
866            return getStaticOverlayPaths(targetPackageName, targetPath);
867        }
868    }
869
870    class ParallelPackageParserCallback extends PackageParserCallback {
871        List<PackageParser.Package> mOverlayPackages = null;
872
873        void findStaticOverlayPackages() {
874            synchronized (mPackages) {
875                for (PackageParser.Package p : mPackages.values()) {
876                    if (p.mOverlayIsStatic) {
877                        if (mOverlayPackages == null) {
878                            mOverlayPackages = new ArrayList<PackageParser.Package>();
879                        }
880                        mOverlayPackages.add(p);
881                    }
882                }
883            }
884        }
885
886        @Override
887        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
888            // We can trust mOverlayPackages without holding mPackages because package uninstall
889            // can't happen while running parallel parsing.
890            // And we can call mInstaller inside getStaticOverlayPaths without holding mInstallLock
891            // because mInstallLock is held before running parallel parsing.
892            // Moreover holding mPackages or mInstallLock on each parsing thread causes dead-lock.
893            return mOverlayPackages == null ? null :
894                    getStaticOverlayPaths(
895                            getStaticOverlayPackages(mOverlayPackages, targetPackageName),
896                            targetPath);
897        }
898    }
899
900    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
901    final ParallelPackageParserCallback mParallelPackageParserCallback =
902            new ParallelPackageParserCallback();
903
904    public static final class SharedLibraryEntry {
905        public final @Nullable String path;
906        public final @Nullable String apk;
907        public final @NonNull SharedLibraryInfo info;
908
909        SharedLibraryEntry(String _path, String _apk, String name, long version, int type,
910                String declaringPackageName, long declaringPackageVersionCode) {
911            path = _path;
912            apk = _apk;
913            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
914                    declaringPackageName, declaringPackageVersionCode), null);
915        }
916    }
917
918    // Currently known shared libraries.
919    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
920    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
921            new ArrayMap<>();
922
923    // All available activities, for your resolving pleasure.
924    final ActivityIntentResolver mActivities =
925            new ActivityIntentResolver();
926
927    // All available receivers, for your resolving pleasure.
928    final ActivityIntentResolver mReceivers =
929            new ActivityIntentResolver();
930
931    // All available services, for your resolving pleasure.
932    final ServiceIntentResolver mServices = new ServiceIntentResolver();
933
934    // All available providers, for your resolving pleasure.
935    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
936
937    // Mapping from provider base names (first directory in content URI codePath)
938    // to the provider information.
939    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
940            new ArrayMap<String, PackageParser.Provider>();
941
942    // Mapping from instrumentation class names to info about them.
943    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
944            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
945
946    // Packages whose data we have transfered into another package, thus
947    // should no longer exist.
948    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
949
950    // Broadcast actions that are only available to the system.
951    @GuardedBy("mProtectedBroadcasts")
952    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
953
954    /** List of packages waiting for verification. */
955    final SparseArray<PackageVerificationState> mPendingVerification
956            = new SparseArray<PackageVerificationState>();
957
958    final PackageInstallerService mInstallerService;
959
960    final ArtManagerService mArtManagerService;
961
962    private final PackageDexOptimizer mPackageDexOptimizer;
963    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
964    // is used by other apps).
965    private final DexManager mDexManager;
966
967    private AtomicInteger mNextMoveId = new AtomicInteger();
968    private final MoveCallbacks mMoveCallbacks;
969
970    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
971
972    // Cache of users who need badging.
973    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
974
975    /** Token for keys in mPendingVerification. */
976    private int mPendingVerificationToken = 0;
977
978    volatile boolean mSystemReady;
979    volatile boolean mSafeMode;
980    volatile boolean mHasSystemUidErrors;
981    private volatile boolean mWebInstantAppsDisabled;
982
983    ApplicationInfo mAndroidApplication;
984    final ActivityInfo mResolveActivity = new ActivityInfo();
985    final ResolveInfo mResolveInfo = new ResolveInfo();
986    ComponentName mResolveComponentName;
987    PackageParser.Package mPlatformPackage;
988    ComponentName mCustomResolverComponentName;
989
990    boolean mResolverReplaced = false;
991
992    private final @Nullable ComponentName mIntentFilterVerifierComponent;
993    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
994
995    private int mIntentFilterVerificationToken = 0;
996
997    /** The service connection to the ephemeral resolver */
998    final InstantAppResolverConnection mInstantAppResolverConnection;
999    /** Component used to show resolver settings for Instant Apps */
1000    final ComponentName mInstantAppResolverSettingsComponent;
1001
1002    /** Activity used to install instant applications */
1003    ActivityInfo mInstantAppInstallerActivity;
1004    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
1005
1006    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1007            = new SparseArray<IntentFilterVerificationState>();
1008
1009    // TODO remove this and go through mPermissonManager directly
1010    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1011    private final PermissionManagerInternal mPermissionManager;
1012
1013    // List of packages names to keep cached, even if they are uninstalled for all users
1014    private List<String> mKeepUninstalledPackages;
1015
1016    private UserManagerInternal mUserManagerInternal;
1017    private ActivityManagerInternal mActivityManagerInternal;
1018
1019    private DeviceIdleController.LocalService mDeviceIdleController;
1020
1021    private File mCacheDir;
1022
1023    private Future<?> mPrepareAppDataFuture;
1024
1025    private static class IFVerificationParams {
1026        PackageParser.Package pkg;
1027        boolean replacing;
1028        int userId;
1029        int verifierUid;
1030
1031        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1032                int _userId, int _verifierUid) {
1033            pkg = _pkg;
1034            replacing = _replacing;
1035            userId = _userId;
1036            replacing = _replacing;
1037            verifierUid = _verifierUid;
1038        }
1039    }
1040
1041    private interface IntentFilterVerifier<T extends IntentFilter> {
1042        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1043                                               T filter, String packageName);
1044        void startVerifications(int userId);
1045        void receiveVerificationResponse(int verificationId);
1046    }
1047
1048    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1049        private Context mContext;
1050        private ComponentName mIntentFilterVerifierComponent;
1051        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1052
1053        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1054            mContext = context;
1055            mIntentFilterVerifierComponent = verifierComponent;
1056        }
1057
1058        private String getDefaultScheme() {
1059            return IntentFilter.SCHEME_HTTPS;
1060        }
1061
1062        @Override
1063        public void startVerifications(int userId) {
1064            // Launch verifications requests
1065            int count = mCurrentIntentFilterVerifications.size();
1066            for (int n=0; n<count; n++) {
1067                int verificationId = mCurrentIntentFilterVerifications.get(n);
1068                final IntentFilterVerificationState ivs =
1069                        mIntentFilterVerificationStates.get(verificationId);
1070
1071                String packageName = ivs.getPackageName();
1072
1073                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1074                final int filterCount = filters.size();
1075                ArraySet<String> domainsSet = new ArraySet<>();
1076                for (int m=0; m<filterCount; m++) {
1077                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1078                    domainsSet.addAll(filter.getHostsList());
1079                }
1080                synchronized (mPackages) {
1081                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1082                            packageName, domainsSet) != null) {
1083                        scheduleWriteSettingsLocked();
1084                    }
1085                }
1086                sendVerificationRequest(verificationId, ivs);
1087            }
1088            mCurrentIntentFilterVerifications.clear();
1089        }
1090
1091        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1092            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1093            verificationIntent.putExtra(
1094                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1095                    verificationId);
1096            verificationIntent.putExtra(
1097                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1098                    getDefaultScheme());
1099            verificationIntent.putExtra(
1100                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1101                    ivs.getHostsString());
1102            verificationIntent.putExtra(
1103                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1104                    ivs.getPackageName());
1105            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1106            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1107
1108            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1109            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1110                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1111                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1112
1113            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1114            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1115                    "Sending IntentFilter verification broadcast");
1116        }
1117
1118        public void receiveVerificationResponse(int verificationId) {
1119            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1120
1121            final boolean verified = ivs.isVerified();
1122
1123            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1124            final int count = filters.size();
1125            if (DEBUG_DOMAIN_VERIFICATION) {
1126                Slog.i(TAG, "Received verification response " + verificationId
1127                        + " for " + count + " filters, verified=" + verified);
1128            }
1129            for (int n=0; n<count; n++) {
1130                PackageParser.ActivityIntentInfo filter = filters.get(n);
1131                filter.setVerified(verified);
1132
1133                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1134                        + " verified with result:" + verified + " and hosts:"
1135                        + ivs.getHostsString());
1136            }
1137
1138            mIntentFilterVerificationStates.remove(verificationId);
1139
1140            final String packageName = ivs.getPackageName();
1141            IntentFilterVerificationInfo ivi = null;
1142
1143            synchronized (mPackages) {
1144                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1145            }
1146            if (ivi == null) {
1147                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1148                        + verificationId + " packageName:" + packageName);
1149                return;
1150            }
1151            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1152                    "Updating IntentFilterVerificationInfo for package " + packageName
1153                            +" verificationId:" + verificationId);
1154
1155            synchronized (mPackages) {
1156                if (verified) {
1157                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1158                } else {
1159                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1160                }
1161                scheduleWriteSettingsLocked();
1162
1163                final int userId = ivs.getUserId();
1164                if (userId != UserHandle.USER_ALL) {
1165                    final int userStatus =
1166                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1167
1168                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1169                    boolean needUpdate = false;
1170
1171                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1172                    // already been set by the User thru the Disambiguation dialog
1173                    switch (userStatus) {
1174                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1175                            if (verified) {
1176                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1177                            } else {
1178                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1179                            }
1180                            needUpdate = true;
1181                            break;
1182
1183                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1184                            if (verified) {
1185                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1186                                needUpdate = true;
1187                            }
1188                            break;
1189
1190                        default:
1191                            // Nothing to do
1192                    }
1193
1194                    if (needUpdate) {
1195                        mSettings.updateIntentFilterVerificationStatusLPw(
1196                                packageName, updatedStatus, userId);
1197                        scheduleWritePackageRestrictionsLocked(userId);
1198                    }
1199                }
1200            }
1201        }
1202
1203        @Override
1204        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1205                    ActivityIntentInfo filter, String packageName) {
1206            if (!hasValidDomains(filter)) {
1207                return false;
1208            }
1209            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1210            if (ivs == null) {
1211                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1212                        packageName);
1213            }
1214            if (DEBUG_DOMAIN_VERIFICATION) {
1215                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1216            }
1217            ivs.addFilter(filter);
1218            return true;
1219        }
1220
1221        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1222                int userId, int verificationId, String packageName) {
1223            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1224                    verifierUid, userId, packageName);
1225            ivs.setPendingState();
1226            synchronized (mPackages) {
1227                mIntentFilterVerificationStates.append(verificationId, ivs);
1228                mCurrentIntentFilterVerifications.add(verificationId);
1229            }
1230            return ivs;
1231        }
1232    }
1233
1234    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1235        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1236                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1237                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1238    }
1239
1240    // Set of pending broadcasts for aggregating enable/disable of components.
1241    static class PendingPackageBroadcasts {
1242        // for each user id, a map of <package name -> components within that package>
1243        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1244
1245        public PendingPackageBroadcasts() {
1246            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1247        }
1248
1249        public ArrayList<String> get(int userId, String packageName) {
1250            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1251            return packages.get(packageName);
1252        }
1253
1254        public void put(int userId, String packageName, ArrayList<String> components) {
1255            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1256            packages.put(packageName, components);
1257        }
1258
1259        public void remove(int userId, String packageName) {
1260            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1261            if (packages != null) {
1262                packages.remove(packageName);
1263            }
1264        }
1265
1266        public void remove(int userId) {
1267            mUidMap.remove(userId);
1268        }
1269
1270        public int userIdCount() {
1271            return mUidMap.size();
1272        }
1273
1274        public int userIdAt(int n) {
1275            return mUidMap.keyAt(n);
1276        }
1277
1278        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1279            return mUidMap.get(userId);
1280        }
1281
1282        public int size() {
1283            // total number of pending broadcast entries across all userIds
1284            int num = 0;
1285            for (int i = 0; i< mUidMap.size(); i++) {
1286                num += mUidMap.valueAt(i).size();
1287            }
1288            return num;
1289        }
1290
1291        public void clear() {
1292            mUidMap.clear();
1293        }
1294
1295        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1296            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1297            if (map == null) {
1298                map = new ArrayMap<String, ArrayList<String>>();
1299                mUidMap.put(userId, map);
1300            }
1301            return map;
1302        }
1303    }
1304    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1305
1306    // Service Connection to remote media container service to copy
1307    // package uri's from external media onto secure containers
1308    // or internal storage.
1309    private IMediaContainerService mContainerService = null;
1310
1311    static final int SEND_PENDING_BROADCAST = 1;
1312    static final int MCS_BOUND = 3;
1313    static final int END_COPY = 4;
1314    static final int INIT_COPY = 5;
1315    static final int MCS_UNBIND = 6;
1316    static final int START_CLEANING_PACKAGE = 7;
1317    static final int FIND_INSTALL_LOC = 8;
1318    static final int POST_INSTALL = 9;
1319    static final int MCS_RECONNECT = 10;
1320    static final int MCS_GIVE_UP = 11;
1321    static final int WRITE_SETTINGS = 13;
1322    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1323    static final int PACKAGE_VERIFIED = 15;
1324    static final int CHECK_PENDING_VERIFICATION = 16;
1325    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1326    static final int INTENT_FILTER_VERIFIED = 18;
1327    static final int WRITE_PACKAGE_LIST = 19;
1328    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1329    static final int DEF_CONTAINER_BIND = 21;
1330
1331    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1332
1333    // Delay time in millisecs
1334    static final int BROADCAST_DELAY = 10 * 1000;
1335
1336    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1337            2 * 60 * 60 * 1000L; /* two hours */
1338
1339    static UserManagerService sUserManager;
1340
1341    // Stores a list of users whose package restrictions file needs to be updated
1342    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1343
1344    final private DefaultContainerConnection mDefContainerConn =
1345            new DefaultContainerConnection();
1346    class DefaultContainerConnection implements ServiceConnection {
1347        public void onServiceConnected(ComponentName name, IBinder service) {
1348            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1349            final IMediaContainerService imcs = IMediaContainerService.Stub
1350                    .asInterface(Binder.allowBlocking(service));
1351            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1352        }
1353
1354        public void onServiceDisconnected(ComponentName name) {
1355            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1356        }
1357    }
1358
1359    // Recordkeeping of restore-after-install operations that are currently in flight
1360    // between the Package Manager and the Backup Manager
1361    static class PostInstallData {
1362        public InstallArgs args;
1363        public PackageInstalledInfo res;
1364
1365        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1366            args = _a;
1367            res = _r;
1368        }
1369    }
1370
1371    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1372    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1373
1374    // XML tags for backup/restore of various bits of state
1375    private static final String TAG_PREFERRED_BACKUP = "pa";
1376    private static final String TAG_DEFAULT_APPS = "da";
1377    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1378
1379    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1380    private static final String TAG_ALL_GRANTS = "rt-grants";
1381    private static final String TAG_GRANT = "grant";
1382    private static final String ATTR_PACKAGE_NAME = "pkg";
1383
1384    private static final String TAG_PERMISSION = "perm";
1385    private static final String ATTR_PERMISSION_NAME = "name";
1386    private static final String ATTR_IS_GRANTED = "g";
1387    private static final String ATTR_USER_SET = "set";
1388    private static final String ATTR_USER_FIXED = "fixed";
1389    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1390
1391    // System/policy permission grants are not backed up
1392    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1393            FLAG_PERMISSION_POLICY_FIXED
1394            | FLAG_PERMISSION_SYSTEM_FIXED
1395            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1396
1397    // And we back up these user-adjusted states
1398    private static final int USER_RUNTIME_GRANT_MASK =
1399            FLAG_PERMISSION_USER_SET
1400            | FLAG_PERMISSION_USER_FIXED
1401            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1402
1403    final @Nullable String mRequiredVerifierPackage;
1404    final @NonNull String mRequiredInstallerPackage;
1405    final @NonNull String mRequiredUninstallerPackage;
1406    final @Nullable String mSetupWizardPackage;
1407    final @Nullable String mStorageManagerPackage;
1408    final @Nullable String mSystemTextClassifierPackage;
1409    final @NonNull String mServicesSystemSharedLibraryPackageName;
1410    final @NonNull String mSharedSystemSharedLibraryPackageName;
1411
1412    private final PackageUsage mPackageUsage = new PackageUsage();
1413    private final CompilerStats mCompilerStats = new CompilerStats();
1414
1415    class PackageHandler extends Handler {
1416        private boolean mBound = false;
1417        final ArrayList<HandlerParams> mPendingInstalls =
1418            new ArrayList<HandlerParams>();
1419
1420        private boolean connectToService() {
1421            if (DEBUG_INSTALL) Log.i(TAG, "Trying to bind to DefaultContainerService");
1422            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1423            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1424            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1425                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1426                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1427                mBound = true;
1428                return true;
1429            }
1430            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1431            return false;
1432        }
1433
1434        private void disconnectService() {
1435            mContainerService = null;
1436            mBound = false;
1437            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1438            mContext.unbindService(mDefContainerConn);
1439            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1440        }
1441
1442        PackageHandler(Looper looper) {
1443            super(looper);
1444        }
1445
1446        public void handleMessage(Message msg) {
1447            try {
1448                doHandleMessage(msg);
1449            } finally {
1450                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1451            }
1452        }
1453
1454        void doHandleMessage(Message msg) {
1455            switch (msg.what) {
1456                case DEF_CONTAINER_BIND:
1457                    if (!mBound) {
1458                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "earlyBindingMCS",
1459                                System.identityHashCode(mHandler));
1460                        if (!connectToService()) {
1461                            Slog.e(TAG, "Failed to bind to media container service");
1462                        }
1463                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "earlyBindingMCS",
1464                                System.identityHashCode(mHandler));
1465                    }
1466                    break;
1467                case INIT_COPY: {
1468                    HandlerParams params = (HandlerParams) msg.obj;
1469                    int idx = mPendingInstalls.size();
1470                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1471                    // If a bind was already initiated we dont really
1472                    // need to do anything. The pending install
1473                    // will be processed later on.
1474                    if (!mBound) {
1475                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1476                                System.identityHashCode(mHandler));
1477                        // If this is the only one pending we might
1478                        // have to bind to the service again.
1479                        if (!connectToService()) {
1480                            Slog.e(TAG, "Failed to bind to media container service");
1481                            params.serviceError();
1482                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1483                                    System.identityHashCode(mHandler));
1484                            if (params.traceMethod != null) {
1485                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1486                                        params.traceCookie);
1487                            }
1488                            return;
1489                        } else {
1490                            // Once we bind to the service, the first
1491                            // pending request will be processed.
1492                            mPendingInstalls.add(idx, params);
1493                        }
1494                    } else {
1495                        mPendingInstalls.add(idx, params);
1496                        // Already bound to the service. Just make
1497                        // sure we trigger off processing the first request.
1498                        if (idx == 0) {
1499                            mHandler.sendEmptyMessage(MCS_BOUND);
1500                        }
1501                    }
1502                    break;
1503                }
1504                case MCS_BOUND: {
1505                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1506                    if (msg.obj != null) {
1507                        mContainerService = (IMediaContainerService) msg.obj;
1508                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1509                                System.identityHashCode(mHandler));
1510                    }
1511                    if (mContainerService == null) {
1512                        if (!mBound) {
1513                            // Something seriously wrong since we are not bound and we are not
1514                            // waiting for connection. Bail out.
1515                            Slog.e(TAG, "Cannot bind to media container service");
1516                            for (HandlerParams params : mPendingInstalls) {
1517                                // Indicate service bind error
1518                                params.serviceError();
1519                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1520                                        System.identityHashCode(params));
1521                                if (params.traceMethod != null) {
1522                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1523                                            params.traceMethod, params.traceCookie);
1524                                }
1525                            }
1526                            mPendingInstalls.clear();
1527                        } else {
1528                            Slog.w(TAG, "Waiting to connect to media container service");
1529                        }
1530                    } else if (mPendingInstalls.size() > 0) {
1531                        HandlerParams params = mPendingInstalls.get(0);
1532                        if (params != null) {
1533                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1534                                    System.identityHashCode(params));
1535                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1536                            if (params.startCopy()) {
1537                                // We are done...  look for more work or to
1538                                // go idle.
1539                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1540                                        "Checking for more work or unbind...");
1541                                // Delete pending install
1542                                if (mPendingInstalls.size() > 0) {
1543                                    mPendingInstalls.remove(0);
1544                                }
1545                                if (mPendingInstalls.size() == 0) {
1546                                    if (mBound) {
1547                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1548                                                "Posting delayed MCS_UNBIND");
1549                                        removeMessages(MCS_UNBIND);
1550                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1551                                        // Unbind after a little delay, to avoid
1552                                        // continual thrashing.
1553                                        sendMessageDelayed(ubmsg, 10000);
1554                                    }
1555                                } else {
1556                                    // There are more pending requests in queue.
1557                                    // Just post MCS_BOUND message to trigger processing
1558                                    // of next pending install.
1559                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1560                                            "Posting MCS_BOUND for next work");
1561                                    mHandler.sendEmptyMessage(MCS_BOUND);
1562                                }
1563                            }
1564                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1565                        }
1566                    } else {
1567                        // Should never happen ideally.
1568                        Slog.w(TAG, "Empty queue");
1569                    }
1570                    break;
1571                }
1572                case MCS_RECONNECT: {
1573                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1574                    if (mPendingInstalls.size() > 0) {
1575                        if (mBound) {
1576                            disconnectService();
1577                        }
1578                        if (!connectToService()) {
1579                            Slog.e(TAG, "Failed to bind to media container service");
1580                            for (HandlerParams params : mPendingInstalls) {
1581                                // Indicate service bind error
1582                                params.serviceError();
1583                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1584                                        System.identityHashCode(params));
1585                            }
1586                            mPendingInstalls.clear();
1587                        }
1588                    }
1589                    break;
1590                }
1591                case MCS_UNBIND: {
1592                    // If there is no actual work left, then time to unbind.
1593                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1594
1595                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1596                        if (mBound) {
1597                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1598
1599                            disconnectService();
1600                        }
1601                    } else if (mPendingInstalls.size() > 0) {
1602                        // There are more pending requests in queue.
1603                        // Just post MCS_BOUND message to trigger processing
1604                        // of next pending install.
1605                        mHandler.sendEmptyMessage(MCS_BOUND);
1606                    }
1607
1608                    break;
1609                }
1610                case MCS_GIVE_UP: {
1611                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1612                    HandlerParams params = mPendingInstalls.remove(0);
1613                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1614                            System.identityHashCode(params));
1615                    break;
1616                }
1617                case SEND_PENDING_BROADCAST: {
1618                    String packages[];
1619                    ArrayList<String> components[];
1620                    int size = 0;
1621                    int uids[];
1622                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1623                    synchronized (mPackages) {
1624                        if (mPendingBroadcasts == null) {
1625                            return;
1626                        }
1627                        size = mPendingBroadcasts.size();
1628                        if (size <= 0) {
1629                            // Nothing to be done. Just return
1630                            return;
1631                        }
1632                        packages = new String[size];
1633                        components = new ArrayList[size];
1634                        uids = new int[size];
1635                        int i = 0;  // filling out the above arrays
1636
1637                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1638                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1639                            Iterator<Map.Entry<String, ArrayList<String>>> it
1640                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1641                                            .entrySet().iterator();
1642                            while (it.hasNext() && i < size) {
1643                                Map.Entry<String, ArrayList<String>> ent = it.next();
1644                                packages[i] = ent.getKey();
1645                                components[i] = ent.getValue();
1646                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1647                                uids[i] = (ps != null)
1648                                        ? UserHandle.getUid(packageUserId, ps.appId)
1649                                        : -1;
1650                                i++;
1651                            }
1652                        }
1653                        size = i;
1654                        mPendingBroadcasts.clear();
1655                    }
1656                    // Send broadcasts
1657                    for (int i = 0; i < size; i++) {
1658                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1659                    }
1660                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1661                    break;
1662                }
1663                case START_CLEANING_PACKAGE: {
1664                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1665                    final String packageName = (String)msg.obj;
1666                    final int userId = msg.arg1;
1667                    final boolean andCode = msg.arg2 != 0;
1668                    synchronized (mPackages) {
1669                        if (userId == UserHandle.USER_ALL) {
1670                            int[] users = sUserManager.getUserIds();
1671                            for (int user : users) {
1672                                mSettings.addPackageToCleanLPw(
1673                                        new PackageCleanItem(user, packageName, andCode));
1674                            }
1675                        } else {
1676                            mSettings.addPackageToCleanLPw(
1677                                    new PackageCleanItem(userId, packageName, andCode));
1678                        }
1679                    }
1680                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1681                    startCleaningPackages();
1682                } break;
1683                case POST_INSTALL: {
1684                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1685
1686                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1687                    final boolean didRestore = (msg.arg2 != 0);
1688                    mRunningInstalls.delete(msg.arg1);
1689
1690                    if (data != null) {
1691                        InstallArgs args = data.args;
1692                        PackageInstalledInfo parentRes = data.res;
1693
1694                        final boolean grantPermissions = (args.installFlags
1695                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1696                        final boolean killApp = (args.installFlags
1697                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1698                        final boolean virtualPreload = ((args.installFlags
1699                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1700                        final String[] grantedPermissions = args.installGrantPermissions;
1701
1702                        // Handle the parent package
1703                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1704                                virtualPreload, grantedPermissions, didRestore,
1705                                args.installerPackageName, args.observer);
1706
1707                        // Handle the child packages
1708                        final int childCount = (parentRes.addedChildPackages != null)
1709                                ? parentRes.addedChildPackages.size() : 0;
1710                        for (int i = 0; i < childCount; i++) {
1711                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1712                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1713                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1714                                    args.installerPackageName, args.observer);
1715                        }
1716
1717                        // Log tracing if needed
1718                        if (args.traceMethod != null) {
1719                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1720                                    args.traceCookie);
1721                        }
1722                    } else {
1723                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1724                    }
1725
1726                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1727                } break;
1728                case WRITE_SETTINGS: {
1729                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1730                    synchronized (mPackages) {
1731                        removeMessages(WRITE_SETTINGS);
1732                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1733                        mSettings.writeLPr();
1734                        mDirtyUsers.clear();
1735                    }
1736                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1737                } break;
1738                case WRITE_PACKAGE_RESTRICTIONS: {
1739                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1740                    synchronized (mPackages) {
1741                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1742                        for (int userId : mDirtyUsers) {
1743                            mSettings.writePackageRestrictionsLPr(userId);
1744                        }
1745                        mDirtyUsers.clear();
1746                    }
1747                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1748                } break;
1749                case WRITE_PACKAGE_LIST: {
1750                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1751                    synchronized (mPackages) {
1752                        removeMessages(WRITE_PACKAGE_LIST);
1753                        mSettings.writePackageListLPr(msg.arg1);
1754                    }
1755                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1756                } break;
1757                case CHECK_PENDING_VERIFICATION: {
1758                    final int verificationId = msg.arg1;
1759                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1760
1761                    if ((state != null) && !state.timeoutExtended()) {
1762                        final InstallArgs args = state.getInstallArgs();
1763                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1764
1765                        Slog.i(TAG, "Verification timed out for " + originUri);
1766                        mPendingVerification.remove(verificationId);
1767
1768                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1769
1770                        final UserHandle user = args.getUser();
1771                        if (getDefaultVerificationResponse(user)
1772                                == PackageManager.VERIFICATION_ALLOW) {
1773                            Slog.i(TAG, "Continuing with installation of " + originUri);
1774                            state.setVerifierResponse(Binder.getCallingUid(),
1775                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1776                            broadcastPackageVerified(verificationId, originUri,
1777                                    PackageManager.VERIFICATION_ALLOW, user);
1778                            try {
1779                                ret = args.copyApk(mContainerService, true);
1780                            } catch (RemoteException e) {
1781                                Slog.e(TAG, "Could not contact the ContainerService");
1782                            }
1783                        } else {
1784                            broadcastPackageVerified(verificationId, originUri,
1785                                    PackageManager.VERIFICATION_REJECT, user);
1786                        }
1787
1788                        Trace.asyncTraceEnd(
1789                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1790
1791                        processPendingInstall(args, ret);
1792                        mHandler.sendEmptyMessage(MCS_UNBIND);
1793                    }
1794                    break;
1795                }
1796                case PACKAGE_VERIFIED: {
1797                    final int verificationId = msg.arg1;
1798
1799                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1800                    if (state == null) {
1801                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1802                        break;
1803                    }
1804
1805                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1806
1807                    state.setVerifierResponse(response.callerUid, response.code);
1808
1809                    if (state.isVerificationComplete()) {
1810                        mPendingVerification.remove(verificationId);
1811
1812                        final InstallArgs args = state.getInstallArgs();
1813                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1814
1815                        int ret;
1816                        if (state.isInstallAllowed()) {
1817                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1818                            broadcastPackageVerified(verificationId, originUri,
1819                                    response.code, state.getInstallArgs().getUser());
1820                            try {
1821                                ret = args.copyApk(mContainerService, true);
1822                            } catch (RemoteException e) {
1823                                Slog.e(TAG, "Could not contact the ContainerService");
1824                            }
1825                        } else {
1826                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1827                        }
1828
1829                        Trace.asyncTraceEnd(
1830                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1831
1832                        processPendingInstall(args, ret);
1833                        mHandler.sendEmptyMessage(MCS_UNBIND);
1834                    }
1835
1836                    break;
1837                }
1838                case START_INTENT_FILTER_VERIFICATIONS: {
1839                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1840                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1841                            params.replacing, params.pkg);
1842                    break;
1843                }
1844                case INTENT_FILTER_VERIFIED: {
1845                    final int verificationId = msg.arg1;
1846
1847                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1848                            verificationId);
1849                    if (state == null) {
1850                        Slog.w(TAG, "Invalid IntentFilter verification token "
1851                                + verificationId + " received");
1852                        break;
1853                    }
1854
1855                    final int userId = state.getUserId();
1856
1857                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1858                            "Processing IntentFilter verification with token:"
1859                            + verificationId + " and userId:" + userId);
1860
1861                    final IntentFilterVerificationResponse response =
1862                            (IntentFilterVerificationResponse) msg.obj;
1863
1864                    state.setVerifierResponse(response.callerUid, response.code);
1865
1866                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1867                            "IntentFilter verification with token:" + verificationId
1868                            + " and userId:" + userId
1869                            + " is settings verifier response with response code:"
1870                            + response.code);
1871
1872                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1873                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1874                                + response.getFailedDomainsString());
1875                    }
1876
1877                    if (state.isVerificationComplete()) {
1878                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1879                    } else {
1880                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1881                                "IntentFilter verification with token:" + verificationId
1882                                + " was not said to be complete");
1883                    }
1884
1885                    break;
1886                }
1887                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1888                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1889                            mInstantAppResolverConnection,
1890                            (InstantAppRequest) msg.obj,
1891                            mInstantAppInstallerActivity,
1892                            mHandler);
1893                }
1894            }
1895        }
1896    }
1897
1898    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1899        @Override
1900        public void onGidsChanged(int appId, int userId) {
1901            mHandler.post(new Runnable() {
1902                @Override
1903                public void run() {
1904                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1905                }
1906            });
1907        }
1908        @Override
1909        public void onPermissionGranted(int uid, int userId) {
1910            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1911
1912            // Not critical; if this is lost, the application has to request again.
1913            synchronized (mPackages) {
1914                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1915            }
1916        }
1917        @Override
1918        public void onInstallPermissionGranted() {
1919            synchronized (mPackages) {
1920                scheduleWriteSettingsLocked();
1921            }
1922        }
1923        @Override
1924        public void onPermissionRevoked(int uid, int userId) {
1925            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1926
1927            synchronized (mPackages) {
1928                // Critical; after this call the application should never have the permission
1929                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1930            }
1931
1932            final int appId = UserHandle.getAppId(uid);
1933            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1934        }
1935        @Override
1936        public void onInstallPermissionRevoked() {
1937            synchronized (mPackages) {
1938                scheduleWriteSettingsLocked();
1939            }
1940        }
1941        @Override
1942        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1943            synchronized (mPackages) {
1944                for (int userId : updatedUserIds) {
1945                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1946                }
1947            }
1948        }
1949        @Override
1950        public void onInstallPermissionUpdated() {
1951            synchronized (mPackages) {
1952                scheduleWriteSettingsLocked();
1953            }
1954        }
1955        @Override
1956        public void onPermissionRemoved() {
1957            synchronized (mPackages) {
1958                mSettings.writeLPr();
1959            }
1960        }
1961    };
1962
1963    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1964            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1965            boolean launchedForRestore, String installerPackage,
1966            IPackageInstallObserver2 installObserver) {
1967        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1968            // Send the removed broadcasts
1969            if (res.removedInfo != null) {
1970                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1971            }
1972
1973            // Now that we successfully installed the package, grant runtime
1974            // permissions if requested before broadcasting the install. Also
1975            // for legacy apps in permission review mode we clear the permission
1976            // review flag which is used to emulate runtime permissions for
1977            // legacy apps.
1978            if (grantPermissions) {
1979                final int callingUid = Binder.getCallingUid();
1980                mPermissionManager.grantRequestedRuntimePermissions(
1981                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1982                        mPermissionCallback);
1983            }
1984
1985            final boolean update = res.removedInfo != null
1986                    && res.removedInfo.removedPackage != null;
1987            final String installerPackageName =
1988                    res.installerPackageName != null
1989                            ? res.installerPackageName
1990                            : res.removedInfo != null
1991                                    ? res.removedInfo.installerPackageName
1992                                    : null;
1993
1994            // If this is the first time we have child packages for a disabled privileged
1995            // app that had no children, we grant requested runtime permissions to the new
1996            // children if the parent on the system image had them already granted.
1997            if (res.pkg.parentPackage != null) {
1998                final int callingUid = Binder.getCallingUid();
1999                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
2000                        res.pkg, callingUid, mPermissionCallback);
2001            }
2002
2003            synchronized (mPackages) {
2004                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
2005            }
2006
2007            final String packageName = res.pkg.applicationInfo.packageName;
2008
2009            // Determine the set of users who are adding this package for
2010            // the first time vs. those who are seeing an update.
2011            int[] firstUserIds = EMPTY_INT_ARRAY;
2012            int[] firstInstantUserIds = EMPTY_INT_ARRAY;
2013            int[] updateUserIds = EMPTY_INT_ARRAY;
2014            int[] instantUserIds = EMPTY_INT_ARRAY;
2015            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
2016            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
2017            for (int newUser : res.newUsers) {
2018                final boolean isInstantApp = ps.getInstantApp(newUser);
2019                if (allNewUsers) {
2020                    if (isInstantApp) {
2021                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2022                    } else {
2023                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2024                    }
2025                    continue;
2026                }
2027                boolean isNew = true;
2028                for (int origUser : res.origUsers) {
2029                    if (origUser == newUser) {
2030                        isNew = false;
2031                        break;
2032                    }
2033                }
2034                if (isNew) {
2035                    if (isInstantApp) {
2036                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2037                    } else {
2038                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2039                    }
2040                } else {
2041                    if (isInstantApp) {
2042                        instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser);
2043                    } else {
2044                        updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser);
2045                    }
2046                }
2047            }
2048
2049            // Send installed broadcasts if the package is not a static shared lib.
2050            if (res.pkg.staticSharedLibName == null) {
2051                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2052
2053                // Send added for users that see the package for the first time
2054                // sendPackageAddedForNewUsers also deals with system apps
2055                int appId = UserHandle.getAppId(res.uid);
2056                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2057                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2058                        virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds);
2059
2060                // Send added for users that don't see the package for the first time
2061                Bundle extras = new Bundle(1);
2062                extras.putInt(Intent.EXTRA_UID, res.uid);
2063                if (update) {
2064                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2065                }
2066                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2067                        extras, 0 /*flags*/,
2068                        null /*targetPackage*/, null /*finishedReceiver*/,
2069                        updateUserIds, instantUserIds);
2070                if (installerPackageName != null) {
2071                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2072                            extras, 0 /*flags*/,
2073                            installerPackageName, null /*finishedReceiver*/,
2074                            updateUserIds, instantUserIds);
2075                }
2076                // if the required verifier is defined, but, is not the installer of record
2077                // for the package, it gets notified
2078                final boolean notifyVerifier = mRequiredVerifierPackage != null
2079                        && !mRequiredVerifierPackage.equals(installerPackageName);
2080                if (notifyVerifier) {
2081                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2082                            extras, 0 /*flags*/,
2083                            mRequiredVerifierPackage, null /*finishedReceiver*/,
2084                            updateUserIds, instantUserIds);
2085                }
2086
2087                // Send replaced for users that don't see the package for the first time
2088                if (update) {
2089                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2090                            packageName, extras, 0 /*flags*/,
2091                            null /*targetPackage*/, null /*finishedReceiver*/,
2092                            updateUserIds, instantUserIds);
2093                    if (installerPackageName != null) {
2094                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2095                                extras, 0 /*flags*/,
2096                                installerPackageName, null /*finishedReceiver*/,
2097                                updateUserIds, instantUserIds);
2098                    }
2099                    if (notifyVerifier) {
2100                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2101                                extras, 0 /*flags*/,
2102                                mRequiredVerifierPackage, null /*finishedReceiver*/,
2103                                updateUserIds, instantUserIds);
2104                    }
2105                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2106                            null /*package*/, null /*extras*/, 0 /*flags*/,
2107                            packageName /*targetPackage*/,
2108                            null /*finishedReceiver*/, updateUserIds, instantUserIds);
2109                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2110                    // First-install and we did a restore, so we're responsible for the
2111                    // first-launch broadcast.
2112                    if (DEBUG_BACKUP) {
2113                        Slog.i(TAG, "Post-restore of " + packageName
2114                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds));
2115                    }
2116                    sendFirstLaunchBroadcast(packageName, installerPackage,
2117                            firstUserIds, firstInstantUserIds);
2118                }
2119
2120                // Send broadcast package appeared if forward locked/external for all users
2121                // treat asec-hosted packages like removable media on upgrade
2122                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2123                    if (DEBUG_INSTALL) {
2124                        Slog.i(TAG, "upgrading pkg " + res.pkg
2125                                + " is ASEC-hosted -> AVAILABLE");
2126                    }
2127                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2128                    ArrayList<String> pkgList = new ArrayList<>(1);
2129                    pkgList.add(packageName);
2130                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2131                }
2132            }
2133
2134            // Work that needs to happen on first install within each user
2135            if (firstUserIds != null && firstUserIds.length > 0) {
2136                synchronized (mPackages) {
2137                    for (int userId : firstUserIds) {
2138                        // If this app is a browser and it's newly-installed for some
2139                        // users, clear any default-browser state in those users. The
2140                        // app's nature doesn't depend on the user, so we can just check
2141                        // its browser nature in any user and generalize.
2142                        if (packageIsBrowser(packageName, userId)) {
2143                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2144                        }
2145
2146                        // We may also need to apply pending (restored) runtime
2147                        // permission grants within these users.
2148                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2149                    }
2150                }
2151            }
2152
2153            if (allNewUsers && !update) {
2154                notifyPackageAdded(packageName);
2155            }
2156
2157            // Log current value of "unknown sources" setting
2158            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2159                    getUnknownSourcesSettings());
2160
2161            // Remove the replaced package's older resources safely now
2162            // We delete after a gc for applications  on sdcard.
2163            if (res.removedInfo != null && res.removedInfo.args != null) {
2164                Runtime.getRuntime().gc();
2165                synchronized (mInstallLock) {
2166                    res.removedInfo.args.doPostDeleteLI(true);
2167                }
2168            } else {
2169                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2170                // and not block here.
2171                VMRuntime.getRuntime().requestConcurrentGC();
2172            }
2173
2174            // Notify DexManager that the package was installed for new users.
2175            // The updated users should already be indexed and the package code paths
2176            // should not change.
2177            // Don't notify the manager for ephemeral apps as they are not expected to
2178            // survive long enough to benefit of background optimizations.
2179            for (int userId : firstUserIds) {
2180                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2181                // There's a race currently where some install events may interleave with an uninstall.
2182                // This can lead to package info being null (b/36642664).
2183                if (info != null) {
2184                    mDexManager.notifyPackageInstalled(info, userId);
2185                }
2186            }
2187        }
2188
2189        // If someone is watching installs - notify them
2190        if (installObserver != null) {
2191            try {
2192                Bundle extras = extrasForInstallResult(res);
2193                installObserver.onPackageInstalled(res.name, res.returnCode,
2194                        res.returnMsg, extras);
2195            } catch (RemoteException e) {
2196                Slog.i(TAG, "Observer no longer exists.");
2197            }
2198        }
2199    }
2200
2201    private StorageEventListener mStorageListener = new StorageEventListener() {
2202        @Override
2203        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2204            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2205                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2206                    final String volumeUuid = vol.getFsUuid();
2207
2208                    // Clean up any users or apps that were removed or recreated
2209                    // while this volume was missing
2210                    sUserManager.reconcileUsers(volumeUuid);
2211                    reconcileApps(volumeUuid);
2212
2213                    // Clean up any install sessions that expired or were
2214                    // cancelled while this volume was missing
2215                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2216
2217                    loadPrivatePackages(vol);
2218
2219                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2220                    unloadPrivatePackages(vol);
2221                }
2222            }
2223        }
2224
2225        @Override
2226        public void onVolumeForgotten(String fsUuid) {
2227            if (TextUtils.isEmpty(fsUuid)) {
2228                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2229                return;
2230            }
2231
2232            // Remove any apps installed on the forgotten volume
2233            synchronized (mPackages) {
2234                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2235                for (PackageSetting ps : packages) {
2236                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2237                    deletePackageVersioned(new VersionedPackage(ps.name,
2238                            PackageManager.VERSION_CODE_HIGHEST),
2239                            new LegacyPackageDeleteObserver(null).getBinder(),
2240                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2241                    // Try very hard to release any references to this package
2242                    // so we don't risk the system server being killed due to
2243                    // open FDs
2244                    AttributeCache.instance().removePackage(ps.name);
2245                }
2246
2247                mSettings.onVolumeForgotten(fsUuid);
2248                mSettings.writeLPr();
2249            }
2250        }
2251    };
2252
2253    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2254        Bundle extras = null;
2255        switch (res.returnCode) {
2256            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2257                extras = new Bundle();
2258                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2259                        res.origPermission);
2260                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2261                        res.origPackage);
2262                break;
2263            }
2264            case PackageManager.INSTALL_SUCCEEDED: {
2265                extras = new Bundle();
2266                extras.putBoolean(Intent.EXTRA_REPLACING,
2267                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2268                break;
2269            }
2270        }
2271        return extras;
2272    }
2273
2274    void scheduleWriteSettingsLocked() {
2275        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2276            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2277        }
2278    }
2279
2280    void scheduleWritePackageListLocked(int userId) {
2281        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2282            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2283            msg.arg1 = userId;
2284            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2285        }
2286    }
2287
2288    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2289        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2290        scheduleWritePackageRestrictionsLocked(userId);
2291    }
2292
2293    void scheduleWritePackageRestrictionsLocked(int userId) {
2294        final int[] userIds = (userId == UserHandle.USER_ALL)
2295                ? sUserManager.getUserIds() : new int[]{userId};
2296        for (int nextUserId : userIds) {
2297            if (!sUserManager.exists(nextUserId)) return;
2298            mDirtyUsers.add(nextUserId);
2299            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2300                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2301            }
2302        }
2303    }
2304
2305    public static PackageManagerService main(Context context, Installer installer,
2306            boolean factoryTest, boolean onlyCore) {
2307        // Self-check for initial settings.
2308        PackageManagerServiceCompilerMapping.checkProperties();
2309
2310        PackageManagerService m = new PackageManagerService(context, installer,
2311                factoryTest, onlyCore);
2312        m.enableSystemUserPackages();
2313        ServiceManager.addService("package", m);
2314        final PackageManagerNative pmn = m.new PackageManagerNative();
2315        ServiceManager.addService("package_native", pmn);
2316        return m;
2317    }
2318
2319    private void enableSystemUserPackages() {
2320        if (!UserManager.isSplitSystemUser()) {
2321            return;
2322        }
2323        // For system user, enable apps based on the following conditions:
2324        // - app is whitelisted or belong to one of these groups:
2325        //   -- system app which has no launcher icons
2326        //   -- system app which has INTERACT_ACROSS_USERS permission
2327        //   -- system IME app
2328        // - app is not in the blacklist
2329        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2330        Set<String> enableApps = new ArraySet<>();
2331        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2332                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2333                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2334        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2335        enableApps.addAll(wlApps);
2336        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2337                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2338        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2339        enableApps.removeAll(blApps);
2340        Log.i(TAG, "Applications installed for system user: " + enableApps);
2341        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2342                UserHandle.SYSTEM);
2343        final int allAppsSize = allAps.size();
2344        synchronized (mPackages) {
2345            for (int i = 0; i < allAppsSize; i++) {
2346                String pName = allAps.get(i);
2347                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2348                // Should not happen, but we shouldn't be failing if it does
2349                if (pkgSetting == null) {
2350                    continue;
2351                }
2352                boolean install = enableApps.contains(pName);
2353                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2354                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2355                            + " for system user");
2356                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2357                }
2358            }
2359            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2360        }
2361    }
2362
2363    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2364        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2365                Context.DISPLAY_SERVICE);
2366        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2367    }
2368
2369    /**
2370     * Requests that files preopted on a secondary system partition be copied to the data partition
2371     * if possible.  Note that the actual copying of the files is accomplished by init for security
2372     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2373     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2374     */
2375    private static void requestCopyPreoptedFiles() {
2376        final int WAIT_TIME_MS = 100;
2377        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2378        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2379            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2380            // We will wait for up to 100 seconds.
2381            final long timeStart = SystemClock.uptimeMillis();
2382            final long timeEnd = timeStart + 100 * 1000;
2383            long timeNow = timeStart;
2384            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2385                try {
2386                    Thread.sleep(WAIT_TIME_MS);
2387                } catch (InterruptedException e) {
2388                    // Do nothing
2389                }
2390                timeNow = SystemClock.uptimeMillis();
2391                if (timeNow > timeEnd) {
2392                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2393                    Slog.wtf(TAG, "cppreopt did not finish!");
2394                    break;
2395                }
2396            }
2397
2398            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2399        }
2400    }
2401
2402    public PackageManagerService(Context context, Installer installer,
2403            boolean factoryTest, boolean onlyCore) {
2404        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2405        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2406        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2407                SystemClock.uptimeMillis());
2408
2409        if (mSdkVersion <= 0) {
2410            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2411        }
2412
2413        mContext = context;
2414
2415        mFactoryTest = factoryTest;
2416        mOnlyCore = onlyCore;
2417        mMetrics = new DisplayMetrics();
2418        mInstaller = installer;
2419
2420        // Create sub-components that provide services / data. Order here is important.
2421        synchronized (mInstallLock) {
2422        synchronized (mPackages) {
2423            // Expose private service for system components to use.
2424            LocalServices.addService(
2425                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2426            sUserManager = new UserManagerService(context, this,
2427                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2428            mPermissionManager = PermissionManagerService.create(context,
2429                    new DefaultPermissionGrantedCallback() {
2430                        @Override
2431                        public void onDefaultRuntimePermissionsGranted(int userId) {
2432                            synchronized(mPackages) {
2433                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2434                            }
2435                        }
2436                    }, mPackages /*externalLock*/);
2437            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2438            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2439        }
2440        }
2441        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2442                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2443        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2444                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2445        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2446                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2447        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2448                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2449        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2450                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2451        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2452                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2453        mSettings.addSharedUserLPw("android.uid.se", SE_UID,
2454                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2455
2456        String separateProcesses = SystemProperties.get("debug.separate_processes");
2457        if (separateProcesses != null && separateProcesses.length() > 0) {
2458            if ("*".equals(separateProcesses)) {
2459                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2460                mSeparateProcesses = null;
2461                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2462            } else {
2463                mDefParseFlags = 0;
2464                mSeparateProcesses = separateProcesses.split(",");
2465                Slog.w(TAG, "Running with debug.separate_processes: "
2466                        + separateProcesses);
2467            }
2468        } else {
2469            mDefParseFlags = 0;
2470            mSeparateProcesses = null;
2471        }
2472
2473        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2474                "*dexopt*");
2475        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2476                installer, mInstallLock);
2477        mDexManager = new DexManager(mContext, this, mPackageDexOptimizer, installer, mInstallLock,
2478                dexManagerListener);
2479        mArtManagerService = new ArtManagerService(mContext, this, installer, mInstallLock);
2480        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2481
2482        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2483                FgThread.get().getLooper());
2484
2485        getDefaultDisplayMetrics(context, mMetrics);
2486
2487        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2488        SystemConfig systemConfig = SystemConfig.getInstance();
2489        mAvailableFeatures = systemConfig.getAvailableFeatures();
2490        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2491
2492        mProtectedPackages = new ProtectedPackages(mContext);
2493
2494        synchronized (mInstallLock) {
2495        // writer
2496        synchronized (mPackages) {
2497            mHandlerThread = new ServiceThread(TAG,
2498                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2499            mHandlerThread.start();
2500            mHandler = new PackageHandler(mHandlerThread.getLooper());
2501            mProcessLoggingHandler = new ProcessLoggingHandler();
2502            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2503            mInstantAppRegistry = new InstantAppRegistry(this);
2504
2505            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2506            final int builtInLibCount = libConfig.size();
2507            for (int i = 0; i < builtInLibCount; i++) {
2508                String name = libConfig.keyAt(i);
2509                String path = libConfig.valueAt(i);
2510                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2511                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2512            }
2513
2514            SELinuxMMAC.readInstallPolicy();
2515
2516            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2517            FallbackCategoryProvider.loadFallbacks();
2518            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2519
2520            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2521            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2522            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2523
2524            // Clean up orphaned packages for which the code path doesn't exist
2525            // and they are an update to a system app - caused by bug/32321269
2526            final int packageSettingCount = mSettings.mPackages.size();
2527            for (int i = packageSettingCount - 1; i >= 0; i--) {
2528                PackageSetting ps = mSettings.mPackages.valueAt(i);
2529                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2530                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2531                    mSettings.mPackages.removeAt(i);
2532                    mSettings.enableSystemPackageLPw(ps.name);
2533                }
2534            }
2535
2536            if (mFirstBoot) {
2537                requestCopyPreoptedFiles();
2538            }
2539
2540            String customResolverActivity = Resources.getSystem().getString(
2541                    R.string.config_customResolverActivity);
2542            if (TextUtils.isEmpty(customResolverActivity)) {
2543                customResolverActivity = null;
2544            } else {
2545                mCustomResolverComponentName = ComponentName.unflattenFromString(
2546                        customResolverActivity);
2547            }
2548
2549            long startTime = SystemClock.uptimeMillis();
2550
2551            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2552                    startTime);
2553
2554            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2555            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2556
2557            if (bootClassPath == null) {
2558                Slog.w(TAG, "No BOOTCLASSPATH found!");
2559            }
2560
2561            if (systemServerClassPath == null) {
2562                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2563            }
2564
2565            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2566
2567            final VersionInfo ver = mSettings.getInternalVersion();
2568            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2569            if (mIsUpgrade) {
2570                logCriticalInfo(Log.INFO,
2571                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2572            }
2573
2574            // when upgrading from pre-M, promote system app permissions from install to runtime
2575            mPromoteSystemApps =
2576                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2577
2578            // When upgrading from pre-N, we need to handle package extraction like first boot,
2579            // as there is no profiling data available.
2580            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2581
2582            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2583
2584            // save off the names of pre-existing system packages prior to scanning; we don't
2585            // want to automatically grant runtime permissions for new system apps
2586            if (mPromoteSystemApps) {
2587                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2588                while (pkgSettingIter.hasNext()) {
2589                    PackageSetting ps = pkgSettingIter.next();
2590                    if (isSystemApp(ps)) {
2591                        mExistingSystemPackages.add(ps.name);
2592                    }
2593                }
2594            }
2595
2596            mCacheDir = preparePackageParserCache(mIsUpgrade);
2597
2598            // Set flag to monitor and not change apk file paths when
2599            // scanning install directories.
2600            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2601
2602            if (mIsUpgrade || mFirstBoot) {
2603                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2604            }
2605
2606            // Collect vendor/product overlay packages. (Do this before scanning any apps.)
2607            // For security and version matching reason, only consider
2608            // overlay packages if they reside in the right directory.
2609            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2610                    mDefParseFlags
2611                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2612                    scanFlags
2613                    | SCAN_AS_SYSTEM
2614                    | SCAN_AS_VENDOR,
2615                    0);
2616            scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR),
2617                    mDefParseFlags
2618                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2619                    scanFlags
2620                    | SCAN_AS_SYSTEM
2621                    | SCAN_AS_PRODUCT,
2622                    0);
2623
2624            mParallelPackageParserCallback.findStaticOverlayPackages();
2625
2626            // Find base frameworks (resource packages without code).
2627            scanDirTracedLI(frameworkDir,
2628                    mDefParseFlags
2629                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2630                    scanFlags
2631                    | SCAN_NO_DEX
2632                    | SCAN_AS_SYSTEM
2633                    | SCAN_AS_PRIVILEGED,
2634                    0);
2635
2636            // Collect privileged system packages.
2637            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2638            scanDirTracedLI(privilegedAppDir,
2639                    mDefParseFlags
2640                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2641                    scanFlags
2642                    | SCAN_AS_SYSTEM
2643                    | SCAN_AS_PRIVILEGED,
2644                    0);
2645
2646            // Collect ordinary system packages.
2647            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2648            scanDirTracedLI(systemAppDir,
2649                    mDefParseFlags
2650                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2651                    scanFlags
2652                    | SCAN_AS_SYSTEM,
2653                    0);
2654
2655            // Collect privileged vendor packages.
2656            File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
2657            try {
2658                privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
2659            } catch (IOException e) {
2660                // failed to look up canonical path, continue with original one
2661            }
2662            scanDirTracedLI(privilegedVendorAppDir,
2663                    mDefParseFlags
2664                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2665                    scanFlags
2666                    | SCAN_AS_SYSTEM
2667                    | SCAN_AS_VENDOR
2668                    | SCAN_AS_PRIVILEGED,
2669                    0);
2670
2671            // Collect ordinary vendor packages.
2672            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2673            try {
2674                vendorAppDir = vendorAppDir.getCanonicalFile();
2675            } catch (IOException e) {
2676                // failed to look up canonical path, continue with original one
2677            }
2678            scanDirTracedLI(vendorAppDir,
2679                    mDefParseFlags
2680                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2681                    scanFlags
2682                    | SCAN_AS_SYSTEM
2683                    | SCAN_AS_VENDOR,
2684                    0);
2685
2686            // Collect privileged odm packages. /odm is another vendor partition
2687            // other than /vendor.
2688            File privilegedOdmAppDir = new File(Environment.getOdmDirectory(),
2689                        "priv-app");
2690            try {
2691                privilegedOdmAppDir = privilegedOdmAppDir.getCanonicalFile();
2692            } catch (IOException e) {
2693                // failed to look up canonical path, continue with original one
2694            }
2695            scanDirTracedLI(privilegedOdmAppDir,
2696                    mDefParseFlags
2697                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2698                    scanFlags
2699                    | SCAN_AS_SYSTEM
2700                    | SCAN_AS_VENDOR
2701                    | SCAN_AS_PRIVILEGED,
2702                    0);
2703
2704            // Collect ordinary odm packages. /odm is another vendor partition
2705            // other than /vendor.
2706            File odmAppDir = new File(Environment.getOdmDirectory(), "app");
2707            try {
2708                odmAppDir = odmAppDir.getCanonicalFile();
2709            } catch (IOException e) {
2710                // failed to look up canonical path, continue with original one
2711            }
2712            scanDirTracedLI(odmAppDir,
2713                    mDefParseFlags
2714                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2715                    scanFlags
2716                    | SCAN_AS_SYSTEM
2717                    | SCAN_AS_VENDOR,
2718                    0);
2719
2720            // Collect all OEM packages.
2721            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2722            scanDirTracedLI(oemAppDir,
2723                    mDefParseFlags
2724                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2725                    scanFlags
2726                    | SCAN_AS_SYSTEM
2727                    | SCAN_AS_OEM,
2728                    0);
2729
2730            // Collected privileged product packages.
2731            File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
2732            try {
2733                privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile();
2734            } catch (IOException e) {
2735                // failed to look up canonical path, continue with original one
2736            }
2737            scanDirTracedLI(privilegedProductAppDir,
2738                    mDefParseFlags
2739                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2740                    scanFlags
2741                    | SCAN_AS_SYSTEM
2742                    | SCAN_AS_PRODUCT
2743                    | SCAN_AS_PRIVILEGED,
2744                    0);
2745
2746            // Collect ordinary product packages.
2747            File productAppDir = new File(Environment.getProductDirectory(), "app");
2748            try {
2749                productAppDir = productAppDir.getCanonicalFile();
2750            } catch (IOException e) {
2751                // failed to look up canonical path, continue with original one
2752            }
2753            scanDirTracedLI(productAppDir,
2754                    mDefParseFlags
2755                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2756                    scanFlags
2757                    | SCAN_AS_SYSTEM
2758                    | SCAN_AS_PRODUCT,
2759                    0);
2760
2761            // Prune any system packages that no longer exist.
2762            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2763            // Stub packages must either be replaced with full versions in the /data
2764            // partition or be disabled.
2765            final List<String> stubSystemApps = new ArrayList<>();
2766            if (!mOnlyCore) {
2767                // do this first before mucking with mPackages for the "expecting better" case
2768                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2769                while (pkgIterator.hasNext()) {
2770                    final PackageParser.Package pkg = pkgIterator.next();
2771                    if (pkg.isStub) {
2772                        stubSystemApps.add(pkg.packageName);
2773                    }
2774                }
2775
2776                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2777                while (psit.hasNext()) {
2778                    PackageSetting ps = psit.next();
2779
2780                    /*
2781                     * If this is not a system app, it can't be a
2782                     * disable system app.
2783                     */
2784                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2785                        continue;
2786                    }
2787
2788                    /*
2789                     * If the package is scanned, it's not erased.
2790                     */
2791                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2792                    if (scannedPkg != null) {
2793                        /*
2794                         * If the system app is both scanned and in the
2795                         * disabled packages list, then it must have been
2796                         * added via OTA. Remove it from the currently
2797                         * scanned package so the previously user-installed
2798                         * application can be scanned.
2799                         */
2800                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2801                            logCriticalInfo(Log.WARN,
2802                                    "Expecting better updated system app for " + ps.name
2803                                    + "; removing system app.  Last known"
2804                                    + " codePath=" + ps.codePathString
2805                                    + ", versionCode=" + ps.versionCode
2806                                    + "; scanned versionCode=" + scannedPkg.getLongVersionCode());
2807                            removePackageLI(scannedPkg, true);
2808                            mExpectingBetter.put(ps.name, ps.codePath);
2809                        }
2810
2811                        continue;
2812                    }
2813
2814                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2815                        psit.remove();
2816                        logCriticalInfo(Log.WARN, "System package " + ps.name
2817                                + " no longer exists; it's data will be wiped");
2818                        // Actual deletion of code and data will be handled by later
2819                        // reconciliation step
2820                    } else {
2821                        // we still have a disabled system package, but, it still might have
2822                        // been removed. check the code path still exists and check there's
2823                        // still a package. the latter can happen if an OTA keeps the same
2824                        // code path, but, changes the package name.
2825                        final PackageSetting disabledPs =
2826                                mSettings.getDisabledSystemPkgLPr(ps.name);
2827                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2828                                || disabledPs.pkg == null) {
2829                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2830                        }
2831                    }
2832                }
2833            }
2834
2835            //delete tmp files
2836            deleteTempPackageFiles();
2837
2838            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2839
2840            // Remove any shared userIDs that have no associated packages
2841            mSettings.pruneSharedUsersLPw();
2842            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2843            final int systemPackagesCount = mPackages.size();
2844            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2845                    + " ms, packageCount: " + systemPackagesCount
2846                    + " , timePerPackage: "
2847                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2848                    + " , cached: " + cachedSystemApps);
2849            if (mIsUpgrade && systemPackagesCount > 0) {
2850                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2851                        ((int) systemScanTime) / systemPackagesCount);
2852            }
2853            if (!mOnlyCore) {
2854                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2855                        SystemClock.uptimeMillis());
2856                scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2857
2858                scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags
2859                        | PackageParser.PARSE_FORWARD_LOCK,
2860                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2861
2862                // Remove disable package settings for updated system apps that were
2863                // removed via an OTA. If the update is no longer present, remove the
2864                // app completely. Otherwise, revoke their system privileges.
2865                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2866                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2867                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2868                    final String msg;
2869                    if (deletedPkg == null) {
2870                        // should have found an update, but, we didn't; remove everything
2871                        msg = "Updated system package " + deletedAppName
2872                                + " no longer exists; removing its data";
2873                        // Actual deletion of code and data will be handled by later
2874                        // reconciliation step
2875                    } else {
2876                        // found an update; revoke system privileges
2877                        msg = "Updated system package + " + deletedAppName
2878                                + " no longer exists; revoking system privileges";
2879
2880                        // Don't do anything if a stub is removed from the system image. If
2881                        // we were to remove the uncompressed version from the /data partition,
2882                        // this is where it'd be done.
2883
2884                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2885                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2886                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2887                    }
2888                    logCriticalInfo(Log.WARN, msg);
2889                }
2890
2891                /*
2892                 * Make sure all system apps that we expected to appear on
2893                 * the userdata partition actually showed up. If they never
2894                 * appeared, crawl back and revive the system version.
2895                 */
2896                for (int i = 0; i < mExpectingBetter.size(); i++) {
2897                    final String packageName = mExpectingBetter.keyAt(i);
2898                    if (!mPackages.containsKey(packageName)) {
2899                        final File scanFile = mExpectingBetter.valueAt(i);
2900
2901                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2902                                + " but never showed up; reverting to system");
2903
2904                        final @ParseFlags int reparseFlags;
2905                        final @ScanFlags int rescanFlags;
2906                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2907                            reparseFlags =
2908                                    mDefParseFlags |
2909                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2910                            rescanFlags =
2911                                    scanFlags
2912                                    | SCAN_AS_SYSTEM
2913                                    | SCAN_AS_PRIVILEGED;
2914                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2915                            reparseFlags =
2916                                    mDefParseFlags |
2917                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2918                            rescanFlags =
2919                                    scanFlags
2920                                    | SCAN_AS_SYSTEM;
2921                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)
2922                                || FileUtils.contains(privilegedOdmAppDir, scanFile)) {
2923                            reparseFlags =
2924                                    mDefParseFlags |
2925                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2926                            rescanFlags =
2927                                    scanFlags
2928                                    | SCAN_AS_SYSTEM
2929                                    | SCAN_AS_VENDOR
2930                                    | SCAN_AS_PRIVILEGED;
2931                        } else if (FileUtils.contains(vendorAppDir, scanFile)
2932                                || FileUtils.contains(odmAppDir, scanFile)) {
2933                            reparseFlags =
2934                                    mDefParseFlags |
2935                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2936                            rescanFlags =
2937                                    scanFlags
2938                                    | SCAN_AS_SYSTEM
2939                                    | SCAN_AS_VENDOR;
2940                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2941                            reparseFlags =
2942                                    mDefParseFlags |
2943                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2944                            rescanFlags =
2945                                    scanFlags
2946                                    | SCAN_AS_SYSTEM
2947                                    | SCAN_AS_OEM;
2948                        } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) {
2949                            reparseFlags =
2950                                    mDefParseFlags |
2951                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2952                            rescanFlags =
2953                                    scanFlags
2954                                    | SCAN_AS_SYSTEM
2955                                    | SCAN_AS_PRODUCT
2956                                    | SCAN_AS_PRIVILEGED;
2957                        } else if (FileUtils.contains(productAppDir, scanFile)) {
2958                            reparseFlags =
2959                                    mDefParseFlags |
2960                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2961                            rescanFlags =
2962                                    scanFlags
2963                                    | SCAN_AS_SYSTEM
2964                                    | SCAN_AS_PRODUCT;
2965                        } else {
2966                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2967                            continue;
2968                        }
2969
2970                        mSettings.enableSystemPackageLPw(packageName);
2971
2972                        try {
2973                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2974                        } catch (PackageManagerException e) {
2975                            Slog.e(TAG, "Failed to parse original system package: "
2976                                    + e.getMessage());
2977                        }
2978                    }
2979                }
2980
2981                // Uncompress and install any stubbed system applications.
2982                // This must be done last to ensure all stubs are replaced or disabled.
2983                decompressSystemApplications(stubSystemApps, scanFlags);
2984
2985                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2986                                - cachedSystemApps;
2987
2988                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2989                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2990                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2991                        + " ms, packageCount: " + dataPackagesCount
2992                        + " , timePerPackage: "
2993                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2994                        + " , cached: " + cachedNonSystemApps);
2995                if (mIsUpgrade && dataPackagesCount > 0) {
2996                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2997                            ((int) dataScanTime) / dataPackagesCount);
2998                }
2999            }
3000            mExpectingBetter.clear();
3001
3002            // Resolve the storage manager.
3003            mStorageManagerPackage = getStorageManagerPackageName();
3004
3005            // Resolve protected action filters. Only the setup wizard is allowed to
3006            // have a high priority filter for these actions.
3007            mSetupWizardPackage = getSetupWizardPackageName();
3008            if (mProtectedFilters.size() > 0) {
3009                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
3010                    Slog.i(TAG, "No setup wizard;"
3011                        + " All protected intents capped to priority 0");
3012                }
3013                for (ActivityIntentInfo filter : mProtectedFilters) {
3014                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
3015                        if (DEBUG_FILTERS) {
3016                            Slog.i(TAG, "Found setup wizard;"
3017                                + " allow priority " + filter.getPriority() + ";"
3018                                + " package: " + filter.activity.info.packageName
3019                                + " activity: " + filter.activity.className
3020                                + " priority: " + filter.getPriority());
3021                        }
3022                        // skip setup wizard; allow it to keep the high priority filter
3023                        continue;
3024                    }
3025                    if (DEBUG_FILTERS) {
3026                        Slog.i(TAG, "Protected action; cap priority to 0;"
3027                                + " package: " + filter.activity.info.packageName
3028                                + " activity: " + filter.activity.className
3029                                + " origPrio: " + filter.getPriority());
3030                    }
3031                    filter.setPriority(0);
3032                }
3033            }
3034
3035            mSystemTextClassifierPackage = getSystemTextClassifierPackageName();
3036
3037            mDeferProtectedFilters = false;
3038            mProtectedFilters.clear();
3039
3040            // Now that we know all of the shared libraries, update all clients to have
3041            // the correct library paths.
3042            updateAllSharedLibrariesLPw(null);
3043
3044            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
3045                // NOTE: We ignore potential failures here during a system scan (like
3046                // the rest of the commands above) because there's precious little we
3047                // can do about it. A settings error is reported, though.
3048                final List<String> changedAbiCodePath =
3049                        adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
3050                if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
3051                    for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
3052                        final String codePathString = changedAbiCodePath.get(i);
3053                        try {
3054                            mInstaller.rmdex(codePathString,
3055                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
3056                        } catch (InstallerException ignored) {
3057                        }
3058                    }
3059                }
3060                // Adjust seInfo to ensure apps which share a sharedUserId are placed in the same
3061                // SELinux domain.
3062                setting.fixSeInfoLocked();
3063            }
3064
3065            // Now that we know all the packages we are keeping,
3066            // read and update their last usage times.
3067            mPackageUsage.read(mPackages);
3068            mCompilerStats.read();
3069
3070            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
3071                    SystemClock.uptimeMillis());
3072            Slog.i(TAG, "Time to scan packages: "
3073                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
3074                    + " seconds");
3075
3076            // If the platform SDK has changed since the last time we booted,
3077            // we need to re-grant app permission to catch any new ones that
3078            // appear.  This is really a hack, and means that apps can in some
3079            // cases get permissions that the user didn't initially explicitly
3080            // allow...  it would be nice to have some better way to handle
3081            // this situation.
3082            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
3083            if (sdkUpdated) {
3084                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
3085                        + mSdkVersion + "; regranting permissions for internal storage");
3086            }
3087            mPermissionManager.updateAllPermissions(
3088                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
3089                    mPermissionCallback);
3090            ver.sdkVersion = mSdkVersion;
3091
3092            // If this is the first boot or an update from pre-M, and it is a normal
3093            // boot, then we need to initialize the default preferred apps across
3094            // all defined users.
3095            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
3096                for (UserInfo user : sUserManager.getUsers(true)) {
3097                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
3098                    applyFactoryDefaultBrowserLPw(user.id);
3099                    primeDomainVerificationsLPw(user.id);
3100                }
3101            }
3102
3103            // Prepare storage for system user really early during boot,
3104            // since core system apps like SettingsProvider and SystemUI
3105            // can't wait for user to start
3106            final int storageFlags;
3107            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3108                storageFlags = StorageManager.FLAG_STORAGE_DE;
3109            } else {
3110                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
3111            }
3112            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
3113                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
3114                    true /* onlyCoreApps */);
3115            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
3116                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
3117                        Trace.TRACE_TAG_PACKAGE_MANAGER);
3118                traceLog.traceBegin("AppDataFixup");
3119                try {
3120                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
3121                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3122                } catch (InstallerException e) {
3123                    Slog.w(TAG, "Trouble fixing GIDs", e);
3124                }
3125                traceLog.traceEnd();
3126
3127                traceLog.traceBegin("AppDataPrepare");
3128                if (deferPackages == null || deferPackages.isEmpty()) {
3129                    return;
3130                }
3131                int count = 0;
3132                for (String pkgName : deferPackages) {
3133                    PackageParser.Package pkg = null;
3134                    synchronized (mPackages) {
3135                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
3136                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
3137                            pkg = ps.pkg;
3138                        }
3139                    }
3140                    if (pkg != null) {
3141                        synchronized (mInstallLock) {
3142                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
3143                                    true /* maybeMigrateAppData */);
3144                        }
3145                        count++;
3146                    }
3147                }
3148                traceLog.traceEnd();
3149                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3150            }, "prepareAppData");
3151
3152            // If this is first boot after an OTA, and a normal boot, then
3153            // we need to clear code cache directories.
3154            // Note that we do *not* clear the application profiles. These remain valid
3155            // across OTAs and are used to drive profile verification (post OTA) and
3156            // profile compilation (without waiting to collect a fresh set of profiles).
3157            if (mIsUpgrade && !onlyCore) {
3158                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3159                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3160                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3161                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3162                        // No apps are running this early, so no need to freeze
3163                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3164                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3165                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3166                    }
3167                }
3168                ver.fingerprint = Build.FINGERPRINT;
3169            }
3170
3171            checkDefaultBrowser();
3172
3173            // clear only after permissions and other defaults have been updated
3174            mExistingSystemPackages.clear();
3175            mPromoteSystemApps = false;
3176
3177            // All the changes are done during package scanning.
3178            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3179
3180            // can downgrade to reader
3181            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3182            mSettings.writeLPr();
3183            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3184            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3185                    SystemClock.uptimeMillis());
3186
3187            if (!mOnlyCore) {
3188                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3189                mRequiredInstallerPackage = getRequiredInstallerLPr();
3190                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3191                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3192                if (mIntentFilterVerifierComponent != null) {
3193                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3194                            mIntentFilterVerifierComponent);
3195                } else {
3196                    mIntentFilterVerifier = null;
3197                }
3198                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3199                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3200                        SharedLibraryInfo.VERSION_UNDEFINED);
3201                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3202                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3203                        SharedLibraryInfo.VERSION_UNDEFINED);
3204            } else {
3205                mRequiredVerifierPackage = null;
3206                mRequiredInstallerPackage = null;
3207                mRequiredUninstallerPackage = null;
3208                mIntentFilterVerifierComponent = null;
3209                mIntentFilterVerifier = null;
3210                mServicesSystemSharedLibraryPackageName = null;
3211                mSharedSystemSharedLibraryPackageName = null;
3212            }
3213
3214            mInstallerService = new PackageInstallerService(context, this);
3215            final Pair<ComponentName, String> instantAppResolverComponent =
3216                    getInstantAppResolverLPr();
3217            if (instantAppResolverComponent != null) {
3218                if (DEBUG_INSTANT) {
3219                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3220                }
3221                mInstantAppResolverConnection = new InstantAppResolverConnection(
3222                        mContext, instantAppResolverComponent.first,
3223                        instantAppResolverComponent.second);
3224                mInstantAppResolverSettingsComponent =
3225                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3226            } else {
3227                mInstantAppResolverConnection = null;
3228                mInstantAppResolverSettingsComponent = null;
3229            }
3230            updateInstantAppInstallerLocked(null);
3231
3232            // Read and update the usage of dex files.
3233            // Do this at the end of PM init so that all the packages have their
3234            // data directory reconciled.
3235            // At this point we know the code paths of the packages, so we can validate
3236            // the disk file and build the internal cache.
3237            // The usage file is expected to be small so loading and verifying it
3238            // should take a fairly small time compare to the other activities (e.g. package
3239            // scanning).
3240            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3241            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3242            for (int userId : currentUserIds) {
3243                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3244            }
3245            mDexManager.load(userPackages);
3246            if (mIsUpgrade) {
3247                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3248                        (int) (SystemClock.uptimeMillis() - startTime));
3249            }
3250        } // synchronized (mPackages)
3251        } // synchronized (mInstallLock)
3252
3253        // Now after opening every single application zip, make sure they
3254        // are all flushed.  Not really needed, but keeps things nice and
3255        // tidy.
3256        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3257        Runtime.getRuntime().gc();
3258        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3259
3260        // The initial scanning above does many calls into installd while
3261        // holding the mPackages lock, but we're mostly interested in yelling
3262        // once we have a booted system.
3263        mInstaller.setWarnIfHeld(mPackages);
3264
3265        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3266    }
3267
3268    /**
3269     * Uncompress and install stub applications.
3270     * <p>In order to save space on the system partition, some applications are shipped in a
3271     * compressed form. In addition the compressed bits for the full application, the
3272     * system image contains a tiny stub comprised of only the Android manifest.
3273     * <p>During the first boot, attempt to uncompress and install the full application. If
3274     * the application can't be installed for any reason, disable the stub and prevent
3275     * uncompressing the full application during future boots.
3276     * <p>In order to forcefully attempt an installation of a full application, go to app
3277     * settings and enable the application.
3278     */
3279    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3280        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3281            final String pkgName = stubSystemApps.get(i);
3282            // skip if the system package is already disabled
3283            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3284                stubSystemApps.remove(i);
3285                continue;
3286            }
3287            // skip if the package isn't installed (?!); this should never happen
3288            final PackageParser.Package pkg = mPackages.get(pkgName);
3289            if (pkg == null) {
3290                stubSystemApps.remove(i);
3291                continue;
3292            }
3293            // skip if the package has been disabled by the user
3294            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3295            if (ps != null) {
3296                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3297                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3298                    stubSystemApps.remove(i);
3299                    continue;
3300                }
3301            }
3302
3303            if (DEBUG_COMPRESSION) {
3304                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3305            }
3306
3307            // uncompress the binary to its eventual destination on /data
3308            final File scanFile = decompressPackage(pkg);
3309            if (scanFile == null) {
3310                continue;
3311            }
3312
3313            // install the package to replace the stub on /system
3314            try {
3315                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3316                removePackageLI(pkg, true /*chatty*/);
3317                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3318                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3319                        UserHandle.USER_SYSTEM, "android");
3320                stubSystemApps.remove(i);
3321                continue;
3322            } catch (PackageManagerException e) {
3323                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3324            }
3325
3326            // any failed attempt to install the package will be cleaned up later
3327        }
3328
3329        // disable any stub still left; these failed to install the full application
3330        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3331            final String pkgName = stubSystemApps.get(i);
3332            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3333            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3334                    UserHandle.USER_SYSTEM, "android");
3335            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3336        }
3337    }
3338
3339    /**
3340     * Decompresses the given package on the system image onto
3341     * the /data partition.
3342     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3343     */
3344    private File decompressPackage(PackageParser.Package pkg) {
3345        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3346        if (compressedFiles == null || compressedFiles.length == 0) {
3347            if (DEBUG_COMPRESSION) {
3348                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3349            }
3350            return null;
3351        }
3352        final File dstCodePath =
3353                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3354        int ret = PackageManager.INSTALL_SUCCEEDED;
3355        try {
3356            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3357            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3358            for (File srcFile : compressedFiles) {
3359                final String srcFileName = srcFile.getName();
3360                final String dstFileName = srcFileName.substring(
3361                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3362                final File dstFile = new File(dstCodePath, dstFileName);
3363                ret = decompressFile(srcFile, dstFile);
3364                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3365                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3366                            + "; pkg: " + pkg.packageName
3367                            + ", file: " + dstFileName);
3368                    break;
3369                }
3370            }
3371        } catch (ErrnoException e) {
3372            logCriticalInfo(Log.ERROR, "Failed to decompress"
3373                    + "; pkg: " + pkg.packageName
3374                    + ", err: " + e.errno);
3375        }
3376        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3377            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3378            NativeLibraryHelper.Handle handle = null;
3379            try {
3380                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3381                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3382                        null /*abiOverride*/);
3383            } catch (IOException e) {
3384                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3385                        + "; pkg: " + pkg.packageName);
3386                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3387            } finally {
3388                IoUtils.closeQuietly(handle);
3389            }
3390        }
3391        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3392            if (dstCodePath == null || !dstCodePath.exists()) {
3393                return null;
3394            }
3395            removeCodePathLI(dstCodePath);
3396            return null;
3397        }
3398
3399        return dstCodePath;
3400    }
3401
3402    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3403        // we're only interested in updating the installer appliction when 1) it's not
3404        // already set or 2) the modified package is the installer
3405        if (mInstantAppInstallerActivity != null
3406                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3407                        .equals(modifiedPackage)) {
3408            return;
3409        }
3410        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3411    }
3412
3413    private static File preparePackageParserCache(boolean isUpgrade) {
3414        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3415            return null;
3416        }
3417
3418        // Disable package parsing on eng builds to allow for faster incremental development.
3419        if (Build.IS_ENG) {
3420            return null;
3421        }
3422
3423        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3424            Slog.i(TAG, "Disabling package parser cache due to system property.");
3425            return null;
3426        }
3427
3428        // The base directory for the package parser cache lives under /data/system/.
3429        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3430                "package_cache");
3431        if (cacheBaseDir == null) {
3432            return null;
3433        }
3434
3435        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3436        // This also serves to "GC" unused entries when the package cache version changes (which
3437        // can only happen during upgrades).
3438        if (isUpgrade) {
3439            FileUtils.deleteContents(cacheBaseDir);
3440        }
3441
3442
3443        // Return the versioned package cache directory. This is something like
3444        // "/data/system/package_cache/1"
3445        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3446
3447        if (cacheDir == null) {
3448            // Something went wrong. Attempt to delete everything and return.
3449            Slog.wtf(TAG, "Cache directory cannot be created - wiping base dir " + cacheBaseDir);
3450            FileUtils.deleteContentsAndDir(cacheBaseDir);
3451            return null;
3452        }
3453
3454        // The following is a workaround to aid development on non-numbered userdebug
3455        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3456        // the system partition is newer.
3457        //
3458        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3459        // that starts with "eng." to signify that this is an engineering build and not
3460        // destined for release.
3461        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3462            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3463
3464            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3465            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3466            // in general and should not be used for production changes. In this specific case,
3467            // we know that they will work.
3468            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3469            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3470                FileUtils.deleteContents(cacheBaseDir);
3471                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3472            }
3473        }
3474
3475        return cacheDir;
3476    }
3477
3478    @Override
3479    public boolean isFirstBoot() {
3480        // allow instant applications
3481        return mFirstBoot;
3482    }
3483
3484    @Override
3485    public boolean isOnlyCoreApps() {
3486        // allow instant applications
3487        return mOnlyCore;
3488    }
3489
3490    @Override
3491    public boolean isUpgrade() {
3492        // allow instant applications
3493        // The system property allows testing ota flow when upgraded to the same image.
3494        return mIsUpgrade || SystemProperties.getBoolean(
3495                "persist.pm.mock-upgrade", false /* default */);
3496    }
3497
3498    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3499        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3500
3501        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3502                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3503                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3504        if (matches.size() == 1) {
3505            return matches.get(0).getComponentInfo().packageName;
3506        } else if (matches.size() == 0) {
3507            Log.e(TAG, "There should probably be a verifier, but, none were found");
3508            return null;
3509        }
3510        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3511    }
3512
3513    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3514        synchronized (mPackages) {
3515            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3516            if (libraryEntry == null) {
3517                throw new IllegalStateException("Missing required shared library:" + name);
3518            }
3519            return libraryEntry.apk;
3520        }
3521    }
3522
3523    private @NonNull String getRequiredInstallerLPr() {
3524        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3525        intent.addCategory(Intent.CATEGORY_DEFAULT);
3526        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3527
3528        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3529                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3530                UserHandle.USER_SYSTEM);
3531        if (matches.size() == 1) {
3532            ResolveInfo resolveInfo = matches.get(0);
3533            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3534                throw new RuntimeException("The installer must be a privileged app");
3535            }
3536            return matches.get(0).getComponentInfo().packageName;
3537        } else {
3538            throw new RuntimeException("There must be exactly one installer; found " + matches);
3539        }
3540    }
3541
3542    private @NonNull String getRequiredUninstallerLPr() {
3543        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3544        intent.addCategory(Intent.CATEGORY_DEFAULT);
3545        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3546
3547        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3548                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3549                UserHandle.USER_SYSTEM);
3550        if (resolveInfo == null ||
3551                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3552            throw new RuntimeException("There must be exactly one uninstaller; found "
3553                    + resolveInfo);
3554        }
3555        return resolveInfo.getComponentInfo().packageName;
3556    }
3557
3558    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3559        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3560
3561        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3562                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3563                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3564        ResolveInfo best = null;
3565        final int N = matches.size();
3566        for (int i = 0; i < N; i++) {
3567            final ResolveInfo cur = matches.get(i);
3568            final String packageName = cur.getComponentInfo().packageName;
3569            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3570                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3571                continue;
3572            }
3573
3574            if (best == null || cur.priority > best.priority) {
3575                best = cur;
3576            }
3577        }
3578
3579        if (best != null) {
3580            return best.getComponentInfo().getComponentName();
3581        }
3582        Slog.w(TAG, "Intent filter verifier not found");
3583        return null;
3584    }
3585
3586    @Override
3587    public @Nullable ComponentName getInstantAppResolverComponent() {
3588        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3589            return null;
3590        }
3591        synchronized (mPackages) {
3592            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3593            if (instantAppResolver == null) {
3594                return null;
3595            }
3596            return instantAppResolver.first;
3597        }
3598    }
3599
3600    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3601        final String[] packageArray =
3602                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3603        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3604            if (DEBUG_INSTANT) {
3605                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3606            }
3607            return null;
3608        }
3609
3610        final int callingUid = Binder.getCallingUid();
3611        final int resolveFlags =
3612                MATCH_DIRECT_BOOT_AWARE
3613                | MATCH_DIRECT_BOOT_UNAWARE
3614                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3615        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3616        final Intent resolverIntent = new Intent(actionName);
3617        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3618                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3619        final int N = resolvers.size();
3620        if (N == 0) {
3621            if (DEBUG_INSTANT) {
3622                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3623            }
3624            return null;
3625        }
3626
3627        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3628        for (int i = 0; i < N; i++) {
3629            final ResolveInfo info = resolvers.get(i);
3630
3631            if (info.serviceInfo == null) {
3632                continue;
3633            }
3634
3635            final String packageName = info.serviceInfo.packageName;
3636            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3637                if (DEBUG_INSTANT) {
3638                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3639                            + " pkg: " + packageName + ", info:" + info);
3640                }
3641                continue;
3642            }
3643
3644            if (DEBUG_INSTANT) {
3645                Slog.v(TAG, "Ephemeral resolver found;"
3646                        + " pkg: " + packageName + ", info:" + info);
3647            }
3648            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3649        }
3650        if (DEBUG_INSTANT) {
3651            Slog.v(TAG, "Ephemeral resolver NOT found");
3652        }
3653        return null;
3654    }
3655
3656    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3657        String[] orderedActions = Build.IS_ENG
3658                ? new String[]{
3659                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST",
3660                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}
3661                : new String[]{
3662                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE};
3663
3664        final int resolveFlags =
3665                MATCH_DIRECT_BOOT_AWARE
3666                        | MATCH_DIRECT_BOOT_UNAWARE
3667                        | Intent.FLAG_IGNORE_EPHEMERAL
3668                        | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0);
3669        final Intent intent = new Intent();
3670        intent.addCategory(Intent.CATEGORY_DEFAULT);
3671        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3672        List<ResolveInfo> matches = null;
3673        for (String action : orderedActions) {
3674            intent.setAction(action);
3675            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3676                    resolveFlags, UserHandle.USER_SYSTEM);
3677            if (matches.isEmpty()) {
3678                if (DEBUG_INSTANT) {
3679                    Slog.d(TAG, "Instant App installer not found with " + action);
3680                }
3681            } else {
3682                break;
3683            }
3684        }
3685        Iterator<ResolveInfo> iter = matches.iterator();
3686        while (iter.hasNext()) {
3687            final ResolveInfo rInfo = iter.next();
3688            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3689            if (ps != null) {
3690                final PermissionsState permissionsState = ps.getPermissionsState();
3691                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)
3692                        || Build.IS_ENG) {
3693                    continue;
3694                }
3695            }
3696            iter.remove();
3697        }
3698        if (matches.size() == 0) {
3699            return null;
3700        } else if (matches.size() == 1) {
3701            return (ActivityInfo) matches.get(0).getComponentInfo();
3702        } else {
3703            throw new RuntimeException(
3704                    "There must be at most one ephemeral installer; found " + matches);
3705        }
3706    }
3707
3708    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3709            @NonNull ComponentName resolver) {
3710        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3711                .addCategory(Intent.CATEGORY_DEFAULT)
3712                .setPackage(resolver.getPackageName());
3713        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3714        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3715                UserHandle.USER_SYSTEM);
3716        if (matches.isEmpty()) {
3717            return null;
3718        }
3719        return matches.get(0).getComponentInfo().getComponentName();
3720    }
3721
3722    private void primeDomainVerificationsLPw(int userId) {
3723        if (DEBUG_DOMAIN_VERIFICATION) {
3724            Slog.d(TAG, "Priming domain verifications in user " + userId);
3725        }
3726
3727        SystemConfig systemConfig = SystemConfig.getInstance();
3728        ArraySet<String> packages = systemConfig.getLinkedApps();
3729
3730        for (String packageName : packages) {
3731            PackageParser.Package pkg = mPackages.get(packageName);
3732            if (pkg != null) {
3733                if (!pkg.isSystem()) {
3734                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3735                    continue;
3736                }
3737
3738                ArraySet<String> domains = null;
3739                for (PackageParser.Activity a : pkg.activities) {
3740                    for (ActivityIntentInfo filter : a.intents) {
3741                        if (hasValidDomains(filter)) {
3742                            if (domains == null) {
3743                                domains = new ArraySet<String>();
3744                            }
3745                            domains.addAll(filter.getHostsList());
3746                        }
3747                    }
3748                }
3749
3750                if (domains != null && domains.size() > 0) {
3751                    if (DEBUG_DOMAIN_VERIFICATION) {
3752                        Slog.v(TAG, "      + " + packageName);
3753                    }
3754                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3755                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3756                    // and then 'always' in the per-user state actually used for intent resolution.
3757                    final IntentFilterVerificationInfo ivi;
3758                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3759                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3760                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3761                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3762                } else {
3763                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3764                            + "' does not handle web links");
3765                }
3766            } else {
3767                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3768            }
3769        }
3770
3771        scheduleWritePackageRestrictionsLocked(userId);
3772        scheduleWriteSettingsLocked();
3773    }
3774
3775    private void applyFactoryDefaultBrowserLPw(int userId) {
3776        // The default browser app's package name is stored in a string resource,
3777        // with a product-specific overlay used for vendor customization.
3778        String browserPkg = mContext.getResources().getString(
3779                com.android.internal.R.string.default_browser);
3780        if (!TextUtils.isEmpty(browserPkg)) {
3781            // non-empty string => required to be a known package
3782            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3783            if (ps == null) {
3784                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3785                browserPkg = null;
3786            } else {
3787                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3788            }
3789        }
3790
3791        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3792        // default.  If there's more than one, just leave everything alone.
3793        if (browserPkg == null) {
3794            calculateDefaultBrowserLPw(userId);
3795        }
3796    }
3797
3798    private void calculateDefaultBrowserLPw(int userId) {
3799        List<String> allBrowsers = resolveAllBrowserApps(userId);
3800        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3801        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3802    }
3803
3804    private List<String> resolveAllBrowserApps(int userId) {
3805        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3806        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3807                PackageManager.MATCH_ALL, userId);
3808
3809        final int count = list.size();
3810        List<String> result = new ArrayList<String>(count);
3811        for (int i=0; i<count; i++) {
3812            ResolveInfo info = list.get(i);
3813            if (info.activityInfo == null
3814                    || !info.handleAllWebDataURI
3815                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3816                    || result.contains(info.activityInfo.packageName)) {
3817                continue;
3818            }
3819            result.add(info.activityInfo.packageName);
3820        }
3821
3822        return result;
3823    }
3824
3825    private boolean packageIsBrowser(String packageName, int userId) {
3826        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3827                PackageManager.MATCH_ALL, userId);
3828        final int N = list.size();
3829        for (int i = 0; i < N; i++) {
3830            ResolveInfo info = list.get(i);
3831            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3832                return true;
3833            }
3834        }
3835        return false;
3836    }
3837
3838    private void checkDefaultBrowser() {
3839        final int myUserId = UserHandle.myUserId();
3840        final String packageName = getDefaultBrowserPackageName(myUserId);
3841        if (packageName != null) {
3842            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3843            if (info == null) {
3844                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3845                synchronized (mPackages) {
3846                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3847                }
3848            }
3849        }
3850    }
3851
3852    @Override
3853    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3854            throws RemoteException {
3855        try {
3856            return super.onTransact(code, data, reply, flags);
3857        } catch (RuntimeException e) {
3858            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3859                Slog.wtf(TAG, "Package Manager Crash", e);
3860            }
3861            throw e;
3862        }
3863    }
3864
3865    static int[] appendInts(int[] cur, int[] add) {
3866        if (add == null) return cur;
3867        if (cur == null) return add;
3868        final int N = add.length;
3869        for (int i=0; i<N; i++) {
3870            cur = appendInt(cur, add[i]);
3871        }
3872        return cur;
3873    }
3874
3875    /**
3876     * Returns whether or not a full application can see an instant application.
3877     * <p>
3878     * Currently, there are three cases in which this can occur:
3879     * <ol>
3880     * <li>The calling application is a "special" process. Special processes
3881     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3882     * <li>The calling application has the permission
3883     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3884     * <li>The calling application is the default launcher on the
3885     *     system partition.</li>
3886     * </ol>
3887     */
3888    private boolean canViewInstantApps(int callingUid, int userId) {
3889        if (callingUid < Process.FIRST_APPLICATION_UID) {
3890            return true;
3891        }
3892        if (mContext.checkCallingOrSelfPermission(
3893                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3894            return true;
3895        }
3896        if (mContext.checkCallingOrSelfPermission(
3897                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3898            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3899            if (homeComponent != null
3900                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3901                return true;
3902            }
3903        }
3904        return false;
3905    }
3906
3907    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3908        if (!sUserManager.exists(userId)) return null;
3909        if (ps == null) {
3910            return null;
3911        }
3912        final int callingUid = Binder.getCallingUid();
3913        // Filter out ephemeral app metadata:
3914        //   * The system/shell/root can see metadata for any app
3915        //   * An installed app can see metadata for 1) other installed apps
3916        //     and 2) ephemeral apps that have explicitly interacted with it
3917        //   * Ephemeral apps can only see their own data and exposed installed apps
3918        //   * Holding a signature permission allows seeing instant apps
3919        if (filterAppAccessLPr(ps, callingUid, userId)) {
3920            return null;
3921        }
3922
3923        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3924                && ps.isSystem()) {
3925            flags |= MATCH_ANY_USER;
3926        }
3927
3928        final PackageUserState state = ps.readUserState(userId);
3929        PackageParser.Package p = ps.pkg;
3930        if (p != null) {
3931            final PermissionsState permissionsState = ps.getPermissionsState();
3932
3933            // Compute GIDs only if requested
3934            final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3935                    ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3936            // Compute granted permissions only if package has requested permissions
3937            final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3938                    ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3939
3940            PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3941                    ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3942
3943            if (packageInfo == null) {
3944                return null;
3945            }
3946
3947            packageInfo.packageName = packageInfo.applicationInfo.packageName =
3948                    resolveExternalPackageNameLPr(p);
3949
3950            return packageInfo;
3951        } else if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 && state.isAvailable(flags)) {
3952            PackageInfo pi = new PackageInfo();
3953            pi.packageName = ps.name;
3954            pi.setLongVersionCode(ps.versionCode);
3955            pi.sharedUserId = (ps.sharedUser != null) ? ps.sharedUser.name : null;
3956            pi.firstInstallTime = ps.firstInstallTime;
3957            pi.lastUpdateTime = ps.lastUpdateTime;
3958
3959            ApplicationInfo ai = new ApplicationInfo();
3960            ai.packageName = ps.name;
3961            ai.uid = UserHandle.getUid(userId, ps.appId);
3962            ai.primaryCpuAbi = ps.primaryCpuAbiString;
3963            ai.secondaryCpuAbi = ps.secondaryCpuAbiString;
3964            ai.setVersionCode(ps.versionCode);
3965            ai.flags = ps.pkgFlags;
3966            ai.privateFlags = ps.pkgPrivateFlags;
3967            pi.applicationInfo = PackageParser.generateApplicationInfo(ai, flags, state, userId);
3968
3969            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "ps.pkg is n/a for ["
3970                    + ps.name + "]. Provides a minimum info.");
3971            return pi;
3972        } else {
3973            return null;
3974        }
3975    }
3976
3977    @Override
3978    public void checkPackageStartable(String packageName, int userId) {
3979        final int callingUid = Binder.getCallingUid();
3980        if (getInstantAppPackageName(callingUid) != null) {
3981            throw new SecurityException("Instant applications don't have access to this method");
3982        }
3983        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3984        synchronized (mPackages) {
3985            final PackageSetting ps = mSettings.mPackages.get(packageName);
3986            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3987                throw new SecurityException("Package " + packageName + " was not found!");
3988            }
3989
3990            if (!ps.getInstalled(userId)) {
3991                throw new SecurityException(
3992                        "Package " + packageName + " was not installed for user " + userId + "!");
3993            }
3994
3995            if (mSafeMode && !ps.isSystem()) {
3996                throw new SecurityException("Package " + packageName + " not a system app!");
3997            }
3998
3999            if (mFrozenPackages.contains(packageName)) {
4000                throw new SecurityException("Package " + packageName + " is currently frozen!");
4001            }
4002
4003            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
4004                throw new SecurityException("Package " + packageName + " is not encryption aware!");
4005            }
4006        }
4007    }
4008
4009    @Override
4010    public boolean isPackageAvailable(String packageName, int userId) {
4011        if (!sUserManager.exists(userId)) return false;
4012        final int callingUid = Binder.getCallingUid();
4013        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4014                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
4015        synchronized (mPackages) {
4016            PackageParser.Package p = mPackages.get(packageName);
4017            if (p != null) {
4018                final PackageSetting ps = (PackageSetting) p.mExtras;
4019                if (filterAppAccessLPr(ps, callingUid, userId)) {
4020                    return false;
4021                }
4022                if (ps != null) {
4023                    final PackageUserState state = ps.readUserState(userId);
4024                    if (state != null) {
4025                        return PackageParser.isAvailable(state);
4026                    }
4027                }
4028            }
4029        }
4030        return false;
4031    }
4032
4033    @Override
4034    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
4035        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
4036                flags, Binder.getCallingUid(), userId);
4037    }
4038
4039    @Override
4040    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
4041            int flags, int userId) {
4042        return getPackageInfoInternal(versionedPackage.getPackageName(),
4043                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
4044    }
4045
4046    /**
4047     * Important: The provided filterCallingUid is used exclusively to filter out packages
4048     * that can be seen based on user state. It's typically the original caller uid prior
4049     * to clearing. Because it can only be provided by trusted code, it's value can be
4050     * trusted and will be used as-is; unlike userId which will be validated by this method.
4051     */
4052    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
4053            int flags, int filterCallingUid, int userId) {
4054        if (!sUserManager.exists(userId)) return null;
4055        flags = updateFlagsForPackage(flags, userId, packageName);
4056        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4057                false /* requireFullPermission */, false /* checkShell */, "get package info");
4058
4059        // reader
4060        synchronized (mPackages) {
4061            // Normalize package name to handle renamed packages and static libs
4062            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
4063
4064            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
4065            if (matchFactoryOnly) {
4066                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
4067                if (ps != null) {
4068                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4069                        return null;
4070                    }
4071                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4072                        return null;
4073                    }
4074                    return generatePackageInfo(ps, flags, userId);
4075                }
4076            }
4077
4078            PackageParser.Package p = mPackages.get(packageName);
4079            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
4080                return null;
4081            }
4082            if (DEBUG_PACKAGE_INFO)
4083                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
4084            if (p != null) {
4085                final PackageSetting ps = (PackageSetting) p.mExtras;
4086                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4087                    return null;
4088                }
4089                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
4090                    return null;
4091                }
4092                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4093            }
4094            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4095                final PackageSetting ps = mSettings.mPackages.get(packageName);
4096                if (ps == null) return null;
4097                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4098                    return null;
4099                }
4100                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4101                    return null;
4102                }
4103                return generatePackageInfo(ps, flags, userId);
4104            }
4105        }
4106        return null;
4107    }
4108
4109    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4110        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4111            return true;
4112        }
4113        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4114            return true;
4115        }
4116        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4117            return true;
4118        }
4119        return false;
4120    }
4121
4122    private boolean isComponentVisibleToInstantApp(
4123            @Nullable ComponentName component, @ComponentType int type) {
4124        if (type == TYPE_ACTIVITY) {
4125            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4126            if (activity == null) {
4127                return false;
4128            }
4129            final boolean visibleToInstantApp =
4130                    (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4131            final boolean explicitlyVisibleToInstantApp =
4132                    (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
4133            return visibleToInstantApp && explicitlyVisibleToInstantApp;
4134        } else if (type == TYPE_RECEIVER) {
4135            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4136            if (activity == null) {
4137                return false;
4138            }
4139            final boolean visibleToInstantApp =
4140                    (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4141            final boolean explicitlyVisibleToInstantApp =
4142                    (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
4143            return visibleToInstantApp && !explicitlyVisibleToInstantApp;
4144        } else if (type == TYPE_SERVICE) {
4145            final PackageParser.Service service = mServices.mServices.get(component);
4146            return service != null
4147                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4148                    : false;
4149        } else if (type == TYPE_PROVIDER) {
4150            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4151            return provider != null
4152                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4153                    : false;
4154        } else if (type == TYPE_UNKNOWN) {
4155            return isComponentVisibleToInstantApp(component);
4156        }
4157        return false;
4158    }
4159
4160    /**
4161     * Returns whether or not access to the application should be filtered.
4162     * <p>
4163     * Access may be limited based upon whether the calling or target applications
4164     * are instant applications.
4165     *
4166     * @see #canAccessInstantApps(int)
4167     */
4168    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4169            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4170        // if we're in an isolated process, get the real calling UID
4171        if (Process.isIsolated(callingUid)) {
4172            callingUid = mIsolatedOwners.get(callingUid);
4173        }
4174        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4175        final boolean callerIsInstantApp = instantAppPkgName != null;
4176        if (ps == null) {
4177            if (callerIsInstantApp) {
4178                // pretend the application exists, but, needs to be filtered
4179                return true;
4180            }
4181            return false;
4182        }
4183        // if the target and caller are the same application, don't filter
4184        if (isCallerSameApp(ps.name, callingUid)) {
4185            return false;
4186        }
4187        if (callerIsInstantApp) {
4188            // both caller and target are both instant, but, different applications, filter
4189            if (ps.getInstantApp(userId)) {
4190                return true;
4191            }
4192            // request for a specific component; if it hasn't been explicitly exposed through
4193            // property or instrumentation target, filter
4194            if (component != null) {
4195                final PackageParser.Instrumentation instrumentation =
4196                        mInstrumentation.get(component);
4197                if (instrumentation != null
4198                        && isCallerSameApp(instrumentation.info.targetPackage, callingUid)) {
4199                    return false;
4200                }
4201                return !isComponentVisibleToInstantApp(component, componentType);
4202            }
4203            // request for application; if no components have been explicitly exposed, filter
4204            return !ps.pkg.visibleToInstantApps;
4205        }
4206        if (ps.getInstantApp(userId)) {
4207            // caller can see all components of all instant applications, don't filter
4208            if (canViewInstantApps(callingUid, userId)) {
4209                return false;
4210            }
4211            // request for a specific instant application component, filter
4212            if (component != null) {
4213                return true;
4214            }
4215            // request for an instant application; if the caller hasn't been granted access, filter
4216            return !mInstantAppRegistry.isInstantAccessGranted(
4217                    userId, UserHandle.getAppId(callingUid), ps.appId);
4218        }
4219        return false;
4220    }
4221
4222    /**
4223     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4224     */
4225    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4226        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4227    }
4228
4229    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4230            int flags) {
4231        // Callers can access only the libs they depend on, otherwise they need to explicitly
4232        // ask for the shared libraries given the caller is allowed to access all static libs.
4233        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4234            // System/shell/root get to see all static libs
4235            final int appId = UserHandle.getAppId(uid);
4236            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4237                    || appId == Process.ROOT_UID) {
4238                return false;
4239            }
4240            // Installer gets to see all static libs.
4241            if (PackageManager.PERMISSION_GRANTED
4242                    == checkUidPermission(Manifest.permission.INSTALL_PACKAGES, uid)) {
4243                return false;
4244            }
4245        }
4246
4247        // No package means no static lib as it is always on internal storage
4248        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4249            return false;
4250        }
4251
4252        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4253                ps.pkg.staticSharedLibVersion);
4254        if (libEntry == null) {
4255            return false;
4256        }
4257
4258        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4259        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4260        if (uidPackageNames == null) {
4261            return true;
4262        }
4263
4264        for (String uidPackageName : uidPackageNames) {
4265            if (ps.name.equals(uidPackageName)) {
4266                return false;
4267            }
4268            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4269            if (uidPs != null) {
4270                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4271                        libEntry.info.getName());
4272                if (index < 0) {
4273                    continue;
4274                }
4275                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4276                    return false;
4277                }
4278            }
4279        }
4280        return true;
4281    }
4282
4283    @Override
4284    public String[] currentToCanonicalPackageNames(String[] names) {
4285        final int callingUid = Binder.getCallingUid();
4286        if (getInstantAppPackageName(callingUid) != null) {
4287            return names;
4288        }
4289        final String[] out = new String[names.length];
4290        // reader
4291        synchronized (mPackages) {
4292            final int callingUserId = UserHandle.getUserId(callingUid);
4293            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4294            for (int i=names.length-1; i>=0; i--) {
4295                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4296                boolean translateName = false;
4297                if (ps != null && ps.realName != null) {
4298                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4299                    translateName = !targetIsInstantApp
4300                            || canViewInstantApps
4301                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4302                                    UserHandle.getAppId(callingUid), ps.appId);
4303                }
4304                out[i] = translateName ? ps.realName : names[i];
4305            }
4306        }
4307        return out;
4308    }
4309
4310    @Override
4311    public String[] canonicalToCurrentPackageNames(String[] names) {
4312        final int callingUid = Binder.getCallingUid();
4313        if (getInstantAppPackageName(callingUid) != null) {
4314            return names;
4315        }
4316        final String[] out = new String[names.length];
4317        // reader
4318        synchronized (mPackages) {
4319            final int callingUserId = UserHandle.getUserId(callingUid);
4320            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4321            for (int i=names.length-1; i>=0; i--) {
4322                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4323                boolean translateName = false;
4324                if (cur != null) {
4325                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4326                    final boolean targetIsInstantApp =
4327                            ps != null && ps.getInstantApp(callingUserId);
4328                    translateName = !targetIsInstantApp
4329                            || canViewInstantApps
4330                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4331                                    UserHandle.getAppId(callingUid), ps.appId);
4332                }
4333                out[i] = translateName ? cur : names[i];
4334            }
4335        }
4336        return out;
4337    }
4338
4339    @Override
4340    public int getPackageUid(String packageName, int flags, int userId) {
4341        if (!sUserManager.exists(userId)) return -1;
4342        final int callingUid = Binder.getCallingUid();
4343        flags = updateFlagsForPackage(flags, userId, packageName);
4344        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4345                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4346
4347        // reader
4348        synchronized (mPackages) {
4349            final PackageParser.Package p = mPackages.get(packageName);
4350            if (p != null && p.isMatch(flags)) {
4351                PackageSetting ps = (PackageSetting) p.mExtras;
4352                if (filterAppAccessLPr(ps, callingUid, userId)) {
4353                    return -1;
4354                }
4355                return UserHandle.getUid(userId, p.applicationInfo.uid);
4356            }
4357            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4358                final PackageSetting ps = mSettings.mPackages.get(packageName);
4359                if (ps != null && ps.isMatch(flags)
4360                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4361                    return UserHandle.getUid(userId, ps.appId);
4362                }
4363            }
4364        }
4365
4366        return -1;
4367    }
4368
4369    @Override
4370    public int[] getPackageGids(String packageName, int flags, int userId) {
4371        if (!sUserManager.exists(userId)) return null;
4372        final int callingUid = Binder.getCallingUid();
4373        flags = updateFlagsForPackage(flags, userId, packageName);
4374        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4375                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4376
4377        // reader
4378        synchronized (mPackages) {
4379            final PackageParser.Package p = mPackages.get(packageName);
4380            if (p != null && p.isMatch(flags)) {
4381                PackageSetting ps = (PackageSetting) p.mExtras;
4382                if (filterAppAccessLPr(ps, callingUid, userId)) {
4383                    return null;
4384                }
4385                // TODO: Shouldn't this be checking for package installed state for userId and
4386                // return null?
4387                return ps.getPermissionsState().computeGids(userId);
4388            }
4389            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4390                final PackageSetting ps = mSettings.mPackages.get(packageName);
4391                if (ps != null && ps.isMatch(flags)
4392                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4393                    return ps.getPermissionsState().computeGids(userId);
4394                }
4395            }
4396        }
4397
4398        return null;
4399    }
4400
4401    @Override
4402    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4403        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4404    }
4405
4406    @Override
4407    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4408            int flags) {
4409        final List<PermissionInfo> permissionList =
4410                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4411        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4412    }
4413
4414    @Override
4415    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4416        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4417    }
4418
4419    @Override
4420    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4421        final List<PermissionGroupInfo> permissionList =
4422                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4423        return (permissionList == null)
4424                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4425    }
4426
4427    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4428            int filterCallingUid, int userId) {
4429        if (!sUserManager.exists(userId)) return null;
4430        PackageSetting ps = mSettings.mPackages.get(packageName);
4431        if (ps != null) {
4432            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4433                return null;
4434            }
4435            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4436                return null;
4437            }
4438            if (ps.pkg == null) {
4439                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4440                if (pInfo != null) {
4441                    return pInfo.applicationInfo;
4442                }
4443                return null;
4444            }
4445            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4446                    ps.readUserState(userId), userId);
4447            if (ai != null) {
4448                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4449            }
4450            return ai;
4451        }
4452        return null;
4453    }
4454
4455    @Override
4456    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4457        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4458    }
4459
4460    /**
4461     * Important: The provided filterCallingUid is used exclusively to filter out applications
4462     * that can be seen based on user state. It's typically the original caller uid prior
4463     * to clearing. Because it can only be provided by trusted code, it's value can be
4464     * trusted and will be used as-is; unlike userId which will be validated by this method.
4465     */
4466    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4467            int filterCallingUid, int userId) {
4468        if (!sUserManager.exists(userId)) return null;
4469        flags = updateFlagsForApplication(flags, userId, packageName);
4470        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4471                false /* requireFullPermission */, false /* checkShell */, "get application info");
4472
4473        // writer
4474        synchronized (mPackages) {
4475            // Normalize package name to handle renamed packages and static libs
4476            packageName = resolveInternalPackageNameLPr(packageName,
4477                    PackageManager.VERSION_CODE_HIGHEST);
4478
4479            PackageParser.Package p = mPackages.get(packageName);
4480            if (DEBUG_PACKAGE_INFO) Log.v(
4481                    TAG, "getApplicationInfo " + packageName
4482                    + ": " + p);
4483            if (p != null) {
4484                PackageSetting ps = mSettings.mPackages.get(packageName);
4485                if (ps == null) return null;
4486                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4487                    return null;
4488                }
4489                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4490                    return null;
4491                }
4492                // Note: isEnabledLP() does not apply here - always return info
4493                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4494                        p, flags, ps.readUserState(userId), userId);
4495                if (ai != null) {
4496                    ai.packageName = resolveExternalPackageNameLPr(p);
4497                }
4498                return ai;
4499            }
4500            if ("android".equals(packageName)||"system".equals(packageName)) {
4501                return mAndroidApplication;
4502            }
4503            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4504                // Already generates the external package name
4505                return generateApplicationInfoFromSettingsLPw(packageName,
4506                        flags, filterCallingUid, userId);
4507            }
4508        }
4509        return null;
4510    }
4511
4512    private String normalizePackageNameLPr(String packageName) {
4513        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4514        return normalizedPackageName != null ? normalizedPackageName : packageName;
4515    }
4516
4517    @Override
4518    public void deletePreloadsFileCache() {
4519        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4520            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4521        }
4522        File dir = Environment.getDataPreloadsFileCacheDirectory();
4523        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4524        FileUtils.deleteContents(dir);
4525    }
4526
4527    @Override
4528    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4529            final int storageFlags, final IPackageDataObserver observer) {
4530        mContext.enforceCallingOrSelfPermission(
4531                android.Manifest.permission.CLEAR_APP_CACHE, null);
4532        mHandler.post(() -> {
4533            boolean success = false;
4534            try {
4535                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4536                success = true;
4537            } catch (IOException e) {
4538                Slog.w(TAG, e);
4539            }
4540            if (observer != null) {
4541                try {
4542                    observer.onRemoveCompleted(null, success);
4543                } catch (RemoteException e) {
4544                    Slog.w(TAG, e);
4545                }
4546            }
4547        });
4548    }
4549
4550    @Override
4551    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4552            final int storageFlags, final IntentSender pi) {
4553        mContext.enforceCallingOrSelfPermission(
4554                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4555        mHandler.post(() -> {
4556            boolean success = false;
4557            try {
4558                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4559                success = true;
4560            } catch (IOException e) {
4561                Slog.w(TAG, e);
4562            }
4563            if (pi != null) {
4564                try {
4565                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4566                } catch (SendIntentException e) {
4567                    Slog.w(TAG, e);
4568                }
4569            }
4570        });
4571    }
4572
4573    /**
4574     * Blocking call to clear various types of cached data across the system
4575     * until the requested bytes are available.
4576     */
4577    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4578        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4579        final File file = storage.findPathForUuid(volumeUuid);
4580        if (file.getUsableSpace() >= bytes) return;
4581
4582        if (ENABLE_FREE_CACHE_V2) {
4583            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4584                    volumeUuid);
4585            final boolean aggressive = (storageFlags
4586                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4587            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4588
4589            // 1. Pre-flight to determine if we have any chance to succeed
4590            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4591            if (internalVolume && (aggressive || SystemProperties
4592                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4593                deletePreloadsFileCache();
4594                if (file.getUsableSpace() >= bytes) return;
4595            }
4596
4597            // 3. Consider parsed APK data (aggressive only)
4598            if (internalVolume && aggressive) {
4599                FileUtils.deleteContents(mCacheDir);
4600                if (file.getUsableSpace() >= bytes) return;
4601            }
4602
4603            // 4. Consider cached app data (above quotas)
4604            try {
4605                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4606                        Installer.FLAG_FREE_CACHE_V2);
4607            } catch (InstallerException ignored) {
4608            }
4609            if (file.getUsableSpace() >= bytes) return;
4610
4611            // 5. Consider shared libraries with refcount=0 and age>min cache period
4612            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4613                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4614                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4615                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4616                return;
4617            }
4618
4619            // 6. Consider dexopt output (aggressive only)
4620            // TODO: Implement
4621
4622            // 7. Consider installed instant apps unused longer than min cache period
4623            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4624                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4625                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4626                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4627                return;
4628            }
4629
4630            // 8. Consider cached app data (below quotas)
4631            try {
4632                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4633                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4634            } catch (InstallerException ignored) {
4635            }
4636            if (file.getUsableSpace() >= bytes) return;
4637
4638            // 9. Consider DropBox entries
4639            // TODO: Implement
4640
4641            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4642            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4643                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4644                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4645                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4646                return;
4647            }
4648        } else {
4649            try {
4650                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4651            } catch (InstallerException ignored) {
4652            }
4653            if (file.getUsableSpace() >= bytes) return;
4654        }
4655
4656        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4657    }
4658
4659    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4660            throws IOException {
4661        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4662        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4663
4664        List<VersionedPackage> packagesToDelete = null;
4665        final long now = System.currentTimeMillis();
4666
4667        synchronized (mPackages) {
4668            final int[] allUsers = sUserManager.getUserIds();
4669            final int libCount = mSharedLibraries.size();
4670            for (int i = 0; i < libCount; i++) {
4671                final LongSparseArray<SharedLibraryEntry> versionedLib
4672                        = mSharedLibraries.valueAt(i);
4673                if (versionedLib == null) {
4674                    continue;
4675                }
4676                final int versionCount = versionedLib.size();
4677                for (int j = 0; j < versionCount; j++) {
4678                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4679                    // Skip packages that are not static shared libs.
4680                    if (!libInfo.isStatic()) {
4681                        break;
4682                    }
4683                    // Important: We skip static shared libs used for some user since
4684                    // in such a case we need to keep the APK on the device. The check for
4685                    // a lib being used for any user is performed by the uninstall call.
4686                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4687                    // Resolve the package name - we use synthetic package names internally
4688                    final String internalPackageName = resolveInternalPackageNameLPr(
4689                            declaringPackage.getPackageName(),
4690                            declaringPackage.getLongVersionCode());
4691                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4692                    // Skip unused static shared libs cached less than the min period
4693                    // to prevent pruning a lib needed by a subsequently installed package.
4694                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4695                        continue;
4696                    }
4697                    if (packagesToDelete == null) {
4698                        packagesToDelete = new ArrayList<>();
4699                    }
4700                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4701                            declaringPackage.getLongVersionCode()));
4702                }
4703            }
4704        }
4705
4706        if (packagesToDelete != null) {
4707            final int packageCount = packagesToDelete.size();
4708            for (int i = 0; i < packageCount; i++) {
4709                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4710                // Delete the package synchronously (will fail of the lib used for any user).
4711                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4712                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4713                                == PackageManager.DELETE_SUCCEEDED) {
4714                    if (volume.getUsableSpace() >= neededSpace) {
4715                        return true;
4716                    }
4717                }
4718            }
4719        }
4720
4721        return false;
4722    }
4723
4724    /**
4725     * Update given flags based on encryption status of current user.
4726     */
4727    private int updateFlags(int flags, int userId) {
4728        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4729                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4730            // Caller expressed an explicit opinion about what encryption
4731            // aware/unaware components they want to see, so fall through and
4732            // give them what they want
4733        } else {
4734            // Caller expressed no opinion, so match based on user state
4735            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4736                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4737            } else {
4738                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4739            }
4740        }
4741        return flags;
4742    }
4743
4744    private UserManagerInternal getUserManagerInternal() {
4745        if (mUserManagerInternal == null) {
4746            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4747        }
4748        return mUserManagerInternal;
4749    }
4750
4751    private ActivityManagerInternal getActivityManagerInternal() {
4752        if (mActivityManagerInternal == null) {
4753            mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
4754        }
4755        return mActivityManagerInternal;
4756    }
4757
4758
4759    private DeviceIdleController.LocalService getDeviceIdleController() {
4760        if (mDeviceIdleController == null) {
4761            mDeviceIdleController =
4762                    LocalServices.getService(DeviceIdleController.LocalService.class);
4763        }
4764        return mDeviceIdleController;
4765    }
4766
4767    /**
4768     * Update given flags when being used to request {@link PackageInfo}.
4769     */
4770    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4771        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4772        boolean triaged = true;
4773        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4774                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4775            // Caller is asking for component details, so they'd better be
4776            // asking for specific encryption matching behavior, or be triaged
4777            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4778                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4779                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4780                triaged = false;
4781            }
4782        }
4783        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4784                | PackageManager.MATCH_SYSTEM_ONLY
4785                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4786            triaged = false;
4787        }
4788        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4789            // require the permission to be held; the calling uid and given user id referring
4790            // to the same user is not sufficient
4791            mPermissionManager.enforceCrossUserPermission(
4792                    Binder.getCallingUid(), userId, false, false,
4793                    !isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId),
4794                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4795                    + Debug.getCallers(5));
4796        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4797                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4798            // If the caller wants all packages and has a restricted profile associated with it,
4799            // then match all users. This is to make sure that launchers that need to access work
4800            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4801            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4802            flags |= PackageManager.MATCH_ANY_USER;
4803        }
4804        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4805            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4806                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4807        }
4808        return updateFlags(flags, userId);
4809    }
4810
4811    /**
4812     * Update given flags when being used to request {@link ApplicationInfo}.
4813     */
4814    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4815        return updateFlagsForPackage(flags, userId, cookie);
4816    }
4817
4818    /**
4819     * Update given flags when being used to request {@link ComponentInfo}.
4820     */
4821    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4822        if (cookie instanceof Intent) {
4823            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4824                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4825            }
4826        }
4827
4828        boolean triaged = true;
4829        // Caller is asking for component details, so they'd better be
4830        // asking for specific encryption matching behavior, or be triaged
4831        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4832                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4833                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4834            triaged = false;
4835        }
4836        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4837            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4838                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4839        }
4840
4841        return updateFlags(flags, userId);
4842    }
4843
4844    /**
4845     * Update given intent when being used to request {@link ResolveInfo}.
4846     */
4847    private Intent updateIntentForResolve(Intent intent) {
4848        if (intent.getSelector() != null) {
4849            intent = intent.getSelector();
4850        }
4851        if (DEBUG_PREFERRED) {
4852            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4853        }
4854        return intent;
4855    }
4856
4857    /**
4858     * Update given flags when being used to request {@link ResolveInfo}.
4859     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4860     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4861     * flag set. However, this flag is only honoured in three circumstances:
4862     * <ul>
4863     * <li>when called from a system process</li>
4864     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4865     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4866     * action and a {@code android.intent.category.BROWSABLE} category</li>
4867     * </ul>
4868     */
4869    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4870        return updateFlagsForResolve(flags, userId, intent, callingUid,
4871                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4872    }
4873    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4874            boolean wantInstantApps) {
4875        return updateFlagsForResolve(flags, userId, intent, callingUid,
4876                wantInstantApps, false /*onlyExposedExplicitly*/);
4877    }
4878    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4879            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4880        // Safe mode means we shouldn't match any third-party components
4881        if (mSafeMode) {
4882            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4883        }
4884        if (getInstantAppPackageName(callingUid) != null) {
4885            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4886            if (onlyExposedExplicitly) {
4887                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4888            }
4889            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4890            flags |= PackageManager.MATCH_INSTANT;
4891        } else {
4892            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4893            final boolean allowMatchInstant = wantInstantApps
4894                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4895            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4896                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4897            if (!allowMatchInstant) {
4898                flags &= ~PackageManager.MATCH_INSTANT;
4899            }
4900        }
4901        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4902    }
4903
4904    @Override
4905    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4906        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4907    }
4908
4909    /**
4910     * Important: The provided filterCallingUid is used exclusively to filter out activities
4911     * that can be seen based on user state. It's typically the original caller uid prior
4912     * to clearing. Because it can only be provided by trusted code, it's value can be
4913     * trusted and will be used as-is; unlike userId which will be validated by this method.
4914     */
4915    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4916            int filterCallingUid, int userId) {
4917        if (!sUserManager.exists(userId)) return null;
4918        flags = updateFlagsForComponent(flags, userId, component);
4919
4920        if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) {
4921            mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4922                    false /* requireFullPermission */, false /* checkShell */, "get activity info");
4923        }
4924
4925        synchronized (mPackages) {
4926            PackageParser.Activity a = mActivities.mActivities.get(component);
4927
4928            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4929            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4930                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4931                if (ps == null) return null;
4932                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4933                    return null;
4934                }
4935                return PackageParser.generateActivityInfo(
4936                        a, flags, ps.readUserState(userId), userId);
4937            }
4938            if (mResolveComponentName.equals(component)) {
4939                return PackageParser.generateActivityInfo(
4940                        mResolveActivity, flags, new PackageUserState(), userId);
4941            }
4942        }
4943        return null;
4944    }
4945
4946    private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) {
4947        if (!getActivityManagerInternal().isCallerRecents(callingUid)) {
4948            return false;
4949        }
4950        final long token = Binder.clearCallingIdentity();
4951        try {
4952            final int callingUserId = UserHandle.getUserId(callingUid);
4953            if (ActivityManager.getCurrentUser() != callingUserId) {
4954                return false;
4955            }
4956            return sUserManager.isSameProfileGroup(callingUserId, targetUserId);
4957        } finally {
4958            Binder.restoreCallingIdentity(token);
4959        }
4960    }
4961
4962    @Override
4963    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4964            String resolvedType) {
4965        synchronized (mPackages) {
4966            if (component.equals(mResolveComponentName)) {
4967                // The resolver supports EVERYTHING!
4968                return true;
4969            }
4970            final int callingUid = Binder.getCallingUid();
4971            final int callingUserId = UserHandle.getUserId(callingUid);
4972            PackageParser.Activity a = mActivities.mActivities.get(component);
4973            if (a == null) {
4974                return false;
4975            }
4976            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4977            if (ps == null) {
4978                return false;
4979            }
4980            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4981                return false;
4982            }
4983            for (int i=0; i<a.intents.size(); i++) {
4984                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4985                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4986                    return true;
4987                }
4988            }
4989            return false;
4990        }
4991    }
4992
4993    @Override
4994    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4995        if (!sUserManager.exists(userId)) return null;
4996        final int callingUid = Binder.getCallingUid();
4997        flags = updateFlagsForComponent(flags, userId, component);
4998        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4999                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
5000        synchronized (mPackages) {
5001            PackageParser.Activity a = mReceivers.mActivities.get(component);
5002            if (DEBUG_PACKAGE_INFO) Log.v(
5003                TAG, "getReceiverInfo " + component + ": " + a);
5004            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
5005                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5006                if (ps == null) return null;
5007                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
5008                    return null;
5009                }
5010                return PackageParser.generateActivityInfo(
5011                        a, flags, ps.readUserState(userId), userId);
5012            }
5013        }
5014        return null;
5015    }
5016
5017    @Override
5018    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
5019            int flags, int userId) {
5020        if (!sUserManager.exists(userId)) return null;
5021        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
5022        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5023            return null;
5024        }
5025
5026        flags = updateFlagsForPackage(flags, userId, null);
5027
5028        final boolean canSeeStaticLibraries =
5029                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
5030                        == PERMISSION_GRANTED
5031                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
5032                        == PERMISSION_GRANTED
5033                || canRequestPackageInstallsInternal(packageName,
5034                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
5035                        false  /* throwIfPermNotDeclared*/)
5036                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
5037                        == PERMISSION_GRANTED;
5038
5039        synchronized (mPackages) {
5040            List<SharedLibraryInfo> result = null;
5041
5042            final int libCount = mSharedLibraries.size();
5043            for (int i = 0; i < libCount; i++) {
5044                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5045                if (versionedLib == null) {
5046                    continue;
5047                }
5048
5049                final int versionCount = versionedLib.size();
5050                for (int j = 0; j < versionCount; j++) {
5051                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
5052                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
5053                        break;
5054                    }
5055                    final long identity = Binder.clearCallingIdentity();
5056                    try {
5057                        PackageInfo packageInfo = getPackageInfoVersioned(
5058                                libInfo.getDeclaringPackage(), flags
5059                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
5060                        if (packageInfo == null) {
5061                            continue;
5062                        }
5063                    } finally {
5064                        Binder.restoreCallingIdentity(identity);
5065                    }
5066
5067                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
5068                            libInfo.getLongVersion(), libInfo.getType(),
5069                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
5070                            flags, userId));
5071
5072                    if (result == null) {
5073                        result = new ArrayList<>();
5074                    }
5075                    result.add(resLibInfo);
5076                }
5077            }
5078
5079            return result != null ? new ParceledListSlice<>(result) : null;
5080        }
5081    }
5082
5083    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
5084            SharedLibraryInfo libInfo, int flags, int userId) {
5085        List<VersionedPackage> versionedPackages = null;
5086        final int packageCount = mSettings.mPackages.size();
5087        for (int i = 0; i < packageCount; i++) {
5088            PackageSetting ps = mSettings.mPackages.valueAt(i);
5089
5090            if (ps == null) {
5091                continue;
5092            }
5093
5094            if (!ps.getUserState().get(userId).isAvailable(flags)) {
5095                continue;
5096            }
5097
5098            final String libName = libInfo.getName();
5099            if (libInfo.isStatic()) {
5100                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5101                if (libIdx < 0) {
5102                    continue;
5103                }
5104                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
5105                    continue;
5106                }
5107                if (versionedPackages == null) {
5108                    versionedPackages = new ArrayList<>();
5109                }
5110                // If the dependent is a static shared lib, use the public package name
5111                String dependentPackageName = ps.name;
5112                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5113                    dependentPackageName = ps.pkg.manifestPackageName;
5114                }
5115                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5116            } else if (ps.pkg != null) {
5117                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5118                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5119                    if (versionedPackages == null) {
5120                        versionedPackages = new ArrayList<>();
5121                    }
5122                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5123                }
5124            }
5125        }
5126
5127        return versionedPackages;
5128    }
5129
5130    @Override
5131    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5132        if (!sUserManager.exists(userId)) return null;
5133        final int callingUid = Binder.getCallingUid();
5134        flags = updateFlagsForComponent(flags, userId, component);
5135        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5136                false /* requireFullPermission */, false /* checkShell */, "get service info");
5137        synchronized (mPackages) {
5138            PackageParser.Service s = mServices.mServices.get(component);
5139            if (DEBUG_PACKAGE_INFO) Log.v(
5140                TAG, "getServiceInfo " + component + ": " + s);
5141            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5142                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5143                if (ps == null) return null;
5144                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5145                    return null;
5146                }
5147                return PackageParser.generateServiceInfo(
5148                        s, flags, ps.readUserState(userId), userId);
5149            }
5150        }
5151        return null;
5152    }
5153
5154    @Override
5155    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5156        if (!sUserManager.exists(userId)) return null;
5157        final int callingUid = Binder.getCallingUid();
5158        flags = updateFlagsForComponent(flags, userId, component);
5159        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5160                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5161        synchronized (mPackages) {
5162            PackageParser.Provider p = mProviders.mProviders.get(component);
5163            if (DEBUG_PACKAGE_INFO) Log.v(
5164                TAG, "getProviderInfo " + component + ": " + p);
5165            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5166                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5167                if (ps == null) return null;
5168                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5169                    return null;
5170                }
5171                return PackageParser.generateProviderInfo(
5172                        p, flags, ps.readUserState(userId), userId);
5173            }
5174        }
5175        return null;
5176    }
5177
5178    @Override
5179    public String[] getSystemSharedLibraryNames() {
5180        // allow instant applications
5181        synchronized (mPackages) {
5182            Set<String> libs = null;
5183            final int libCount = mSharedLibraries.size();
5184            for (int i = 0; i < libCount; i++) {
5185                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5186                if (versionedLib == null) {
5187                    continue;
5188                }
5189                final int versionCount = versionedLib.size();
5190                for (int j = 0; j < versionCount; j++) {
5191                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5192                    if (!libEntry.info.isStatic()) {
5193                        if (libs == null) {
5194                            libs = new ArraySet<>();
5195                        }
5196                        libs.add(libEntry.info.getName());
5197                        break;
5198                    }
5199                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5200                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5201                            UserHandle.getUserId(Binder.getCallingUid()),
5202                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5203                        if (libs == null) {
5204                            libs = new ArraySet<>();
5205                        }
5206                        libs.add(libEntry.info.getName());
5207                        break;
5208                    }
5209                }
5210            }
5211
5212            if (libs != null) {
5213                String[] libsArray = new String[libs.size()];
5214                libs.toArray(libsArray);
5215                return libsArray;
5216            }
5217
5218            return null;
5219        }
5220    }
5221
5222    @Override
5223    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5224        // allow instant applications
5225        synchronized (mPackages) {
5226            return mServicesSystemSharedLibraryPackageName;
5227        }
5228    }
5229
5230    @Override
5231    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5232        // allow instant applications
5233        synchronized (mPackages) {
5234            return mSharedSystemSharedLibraryPackageName;
5235        }
5236    }
5237
5238    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5239        for (int i = userList.length - 1; i >= 0; --i) {
5240            final int userId = userList[i];
5241            // don't add instant app to the list of updates
5242            if (pkgSetting.getInstantApp(userId)) {
5243                continue;
5244            }
5245            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5246            if (changedPackages == null) {
5247                changedPackages = new SparseArray<>();
5248                mChangedPackages.put(userId, changedPackages);
5249            }
5250            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5251            if (sequenceNumbers == null) {
5252                sequenceNumbers = new HashMap<>();
5253                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5254            }
5255            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5256            if (sequenceNumber != null) {
5257                changedPackages.remove(sequenceNumber);
5258            }
5259            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5260            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5261        }
5262        mChangedPackagesSequenceNumber++;
5263    }
5264
5265    @Override
5266    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5267        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5268            return null;
5269        }
5270        synchronized (mPackages) {
5271            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5272                return null;
5273            }
5274            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5275            if (changedPackages == null) {
5276                return null;
5277            }
5278            final List<String> packageNames =
5279                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5280            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5281                final String packageName = changedPackages.get(i);
5282                if (packageName != null) {
5283                    packageNames.add(packageName);
5284                }
5285            }
5286            return packageNames.isEmpty()
5287                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5288        }
5289    }
5290
5291    @Override
5292    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5293        // allow instant applications
5294        ArrayList<FeatureInfo> res;
5295        synchronized (mAvailableFeatures) {
5296            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5297            res.addAll(mAvailableFeatures.values());
5298        }
5299        final FeatureInfo fi = new FeatureInfo();
5300        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5301                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5302        res.add(fi);
5303
5304        return new ParceledListSlice<>(res);
5305    }
5306
5307    @Override
5308    public boolean hasSystemFeature(String name, int version) {
5309        // allow instant applications
5310        synchronized (mAvailableFeatures) {
5311            final FeatureInfo feat = mAvailableFeatures.get(name);
5312            if (feat == null) {
5313                return false;
5314            } else {
5315                return feat.version >= version;
5316            }
5317        }
5318    }
5319
5320    @Override
5321    public int checkPermission(String permName, String pkgName, int userId) {
5322        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5323    }
5324
5325    @Override
5326    public int checkUidPermission(String permName, int uid) {
5327        synchronized (mPackages) {
5328            final String[] packageNames = getPackagesForUid(uid);
5329            final PackageParser.Package pkg = (packageNames != null && packageNames.length > 0)
5330                    ? mPackages.get(packageNames[0])
5331                    : null;
5332            return mPermissionManager.checkUidPermission(permName, pkg, uid, getCallingUid());
5333        }
5334    }
5335
5336    @Override
5337    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5338        if (UserHandle.getCallingUserId() != userId) {
5339            mContext.enforceCallingPermission(
5340                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5341                    "isPermissionRevokedByPolicy for user " + userId);
5342        }
5343
5344        if (checkPermission(permission, packageName, userId)
5345                == PackageManager.PERMISSION_GRANTED) {
5346            return false;
5347        }
5348
5349        final int callingUid = Binder.getCallingUid();
5350        if (getInstantAppPackageName(callingUid) != null) {
5351            if (!isCallerSameApp(packageName, callingUid)) {
5352                return false;
5353            }
5354        } else {
5355            if (isInstantApp(packageName, userId)) {
5356                return false;
5357            }
5358        }
5359
5360        final long identity = Binder.clearCallingIdentity();
5361        try {
5362            final int flags = getPermissionFlags(permission, packageName, userId);
5363            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5364        } finally {
5365            Binder.restoreCallingIdentity(identity);
5366        }
5367    }
5368
5369    @Override
5370    public String getPermissionControllerPackageName() {
5371        synchronized (mPackages) {
5372            return mRequiredInstallerPackage;
5373        }
5374    }
5375
5376    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5377        return mPermissionManager.addDynamicPermission(
5378                info, async, getCallingUid(), new PermissionCallback() {
5379                    @Override
5380                    public void onPermissionChanged() {
5381                        if (!async) {
5382                            mSettings.writeLPr();
5383                        } else {
5384                            scheduleWriteSettingsLocked();
5385                        }
5386                    }
5387                });
5388    }
5389
5390    @Override
5391    public boolean addPermission(PermissionInfo info) {
5392        synchronized (mPackages) {
5393            return addDynamicPermission(info, false);
5394        }
5395    }
5396
5397    @Override
5398    public boolean addPermissionAsync(PermissionInfo info) {
5399        synchronized (mPackages) {
5400            return addDynamicPermission(info, true);
5401        }
5402    }
5403
5404    @Override
5405    public void removePermission(String permName) {
5406        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5407    }
5408
5409    @Override
5410    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5411        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5412                getCallingUid(), userId, mPermissionCallback);
5413    }
5414
5415    @Override
5416    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5417        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5418                getCallingUid(), userId, mPermissionCallback);
5419    }
5420
5421    @Override
5422    public void resetRuntimePermissions() {
5423        mContext.enforceCallingOrSelfPermission(
5424                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5425                "revokeRuntimePermission");
5426
5427        int callingUid = Binder.getCallingUid();
5428        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5429            mContext.enforceCallingOrSelfPermission(
5430                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5431                    "resetRuntimePermissions");
5432        }
5433
5434        synchronized (mPackages) {
5435            mPermissionManager.updateAllPermissions(
5436                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5437                    mPermissionCallback);
5438            for (int userId : UserManagerService.getInstance().getUserIds()) {
5439                final int packageCount = mPackages.size();
5440                for (int i = 0; i < packageCount; i++) {
5441                    PackageParser.Package pkg = mPackages.valueAt(i);
5442                    if (!(pkg.mExtras instanceof PackageSetting)) {
5443                        continue;
5444                    }
5445                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5446                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5447                }
5448            }
5449        }
5450    }
5451
5452    @Override
5453    public int getPermissionFlags(String permName, String packageName, int userId) {
5454        return mPermissionManager.getPermissionFlags(
5455                permName, packageName, getCallingUid(), userId);
5456    }
5457
5458    @Override
5459    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5460            int flagValues, int userId) {
5461        mPermissionManager.updatePermissionFlags(
5462                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5463                mPermissionCallback);
5464    }
5465
5466    /**
5467     * Update the permission flags for all packages and runtime permissions of a user in order
5468     * to allow device or profile owner to remove POLICY_FIXED.
5469     */
5470    @Override
5471    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5472        synchronized (mPackages) {
5473            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5474                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5475                    mPermissionCallback);
5476            if (changed) {
5477                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5478            }
5479        }
5480    }
5481
5482    @Override
5483    public boolean shouldShowRequestPermissionRationale(String permissionName,
5484            String packageName, int userId) {
5485        if (UserHandle.getCallingUserId() != userId) {
5486            mContext.enforceCallingPermission(
5487                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5488                    "canShowRequestPermissionRationale for user " + userId);
5489        }
5490
5491        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5492        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5493            return false;
5494        }
5495
5496        if (checkPermission(permissionName, packageName, userId)
5497                == PackageManager.PERMISSION_GRANTED) {
5498            return false;
5499        }
5500
5501        final int flags;
5502
5503        final long identity = Binder.clearCallingIdentity();
5504        try {
5505            flags = getPermissionFlags(permissionName,
5506                    packageName, userId);
5507        } finally {
5508            Binder.restoreCallingIdentity(identity);
5509        }
5510
5511        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5512                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5513                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5514
5515        if ((flags & fixedFlags) != 0) {
5516            return false;
5517        }
5518
5519        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5520    }
5521
5522    @Override
5523    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5524        mContext.enforceCallingOrSelfPermission(
5525                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5526                "addOnPermissionsChangeListener");
5527
5528        synchronized (mPackages) {
5529            mOnPermissionChangeListeners.addListenerLocked(listener);
5530        }
5531    }
5532
5533    @Override
5534    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5535        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5536            throw new SecurityException("Instant applications don't have access to this method");
5537        }
5538        synchronized (mPackages) {
5539            mOnPermissionChangeListeners.removeListenerLocked(listener);
5540        }
5541    }
5542
5543    @Override
5544    public boolean isProtectedBroadcast(String actionName) {
5545        // allow instant applications
5546        synchronized (mProtectedBroadcasts) {
5547            if (mProtectedBroadcasts.contains(actionName)) {
5548                return true;
5549            } else if (actionName != null) {
5550                // TODO: remove these terrible hacks
5551                if (actionName.startsWith("android.net.netmon.lingerExpired")
5552                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5553                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5554                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5555                    return true;
5556                }
5557            }
5558        }
5559        return false;
5560    }
5561
5562    @Override
5563    public int checkSignatures(String pkg1, String pkg2) {
5564        synchronized (mPackages) {
5565            final PackageParser.Package p1 = mPackages.get(pkg1);
5566            final PackageParser.Package p2 = mPackages.get(pkg2);
5567            if (p1 == null || p1.mExtras == null
5568                    || p2 == null || p2.mExtras == null) {
5569                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5570            }
5571            final int callingUid = Binder.getCallingUid();
5572            final int callingUserId = UserHandle.getUserId(callingUid);
5573            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5574            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5575            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5576                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5577                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5578            }
5579            return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures);
5580        }
5581    }
5582
5583    @Override
5584    public int checkUidSignatures(int uid1, int uid2) {
5585        final int callingUid = Binder.getCallingUid();
5586        final int callingUserId = UserHandle.getUserId(callingUid);
5587        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5588        // Map to base uids.
5589        uid1 = UserHandle.getAppId(uid1);
5590        uid2 = UserHandle.getAppId(uid2);
5591        // reader
5592        synchronized (mPackages) {
5593            Signature[] s1;
5594            Signature[] s2;
5595            Object obj = mSettings.getUserIdLPr(uid1);
5596            if (obj != null) {
5597                if (obj instanceof SharedUserSetting) {
5598                    if (isCallerInstantApp) {
5599                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5600                    }
5601                    s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5602                } else if (obj instanceof PackageSetting) {
5603                    final PackageSetting ps = (PackageSetting) obj;
5604                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5605                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5606                    }
5607                    s1 = ps.signatures.mSigningDetails.signatures;
5608                } else {
5609                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5610                }
5611            } else {
5612                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5613            }
5614            obj = mSettings.getUserIdLPr(uid2);
5615            if (obj != null) {
5616                if (obj instanceof SharedUserSetting) {
5617                    if (isCallerInstantApp) {
5618                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5619                    }
5620                    s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5621                } else if (obj instanceof PackageSetting) {
5622                    final PackageSetting ps = (PackageSetting) obj;
5623                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5624                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5625                    }
5626                    s2 = ps.signatures.mSigningDetails.signatures;
5627                } else {
5628                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5629                }
5630            } else {
5631                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5632            }
5633            return compareSignatures(s1, s2);
5634        }
5635    }
5636
5637    @Override
5638    public boolean hasSigningCertificate(
5639            String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) {
5640
5641        synchronized (mPackages) {
5642            final PackageParser.Package p = mPackages.get(packageName);
5643            if (p == null || p.mExtras == null) {
5644                return false;
5645            }
5646            final int callingUid = Binder.getCallingUid();
5647            final int callingUserId = UserHandle.getUserId(callingUid);
5648            final PackageSetting ps = (PackageSetting) p.mExtras;
5649            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5650                return false;
5651            }
5652            switch (type) {
5653                case CERT_INPUT_RAW_X509:
5654                    return p.mSigningDetails.hasCertificate(certificate);
5655                case CERT_INPUT_SHA256:
5656                    return p.mSigningDetails.hasSha256Certificate(certificate);
5657                default:
5658                    return false;
5659            }
5660        }
5661    }
5662
5663    @Override
5664    public boolean hasUidSigningCertificate(
5665            int uid, byte[] certificate, @PackageManager.CertificateInputType int type) {
5666        final int callingUid = Binder.getCallingUid();
5667        final int callingUserId = UserHandle.getUserId(callingUid);
5668        // Map to base uids.
5669        uid = UserHandle.getAppId(uid);
5670        // reader
5671        synchronized (mPackages) {
5672            final PackageParser.SigningDetails signingDetails;
5673            final Object obj = mSettings.getUserIdLPr(uid);
5674            if (obj != null) {
5675                if (obj instanceof SharedUserSetting) {
5676                    final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5677                    if (isCallerInstantApp) {
5678                        return false;
5679                    }
5680                    signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails;
5681                } else if (obj instanceof PackageSetting) {
5682                    final PackageSetting ps = (PackageSetting) obj;
5683                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5684                        return false;
5685                    }
5686                    signingDetails = ps.signatures.mSigningDetails;
5687                } else {
5688                    return false;
5689                }
5690            } else {
5691                return false;
5692            }
5693            switch (type) {
5694                case CERT_INPUT_RAW_X509:
5695                    return signingDetails.hasCertificate(certificate);
5696                case CERT_INPUT_SHA256:
5697                    return signingDetails.hasSha256Certificate(certificate);
5698                default:
5699                    return false;
5700            }
5701        }
5702    }
5703
5704    /**
5705     * This method should typically only be used when granting or revoking
5706     * permissions, since the app may immediately restart after this call.
5707     * <p>
5708     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5709     * guard your work against the app being relaunched.
5710     */
5711    private void killUid(int appId, int userId, String reason) {
5712        final long identity = Binder.clearCallingIdentity();
5713        try {
5714            IActivityManager am = ActivityManager.getService();
5715            if (am != null) {
5716                try {
5717                    am.killUid(appId, userId, reason);
5718                } catch (RemoteException e) {
5719                    /* ignore - same process */
5720                }
5721            }
5722        } finally {
5723            Binder.restoreCallingIdentity(identity);
5724        }
5725    }
5726
5727    /**
5728     * If the database version for this type of package (internal storage or
5729     * external storage) is less than the version where package signatures
5730     * were updated, return true.
5731     */
5732    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5733        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5734        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5735    }
5736
5737    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5738        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5739        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5740    }
5741
5742    @Override
5743    public List<String> getAllPackages() {
5744        final int callingUid = Binder.getCallingUid();
5745        final int callingUserId = UserHandle.getUserId(callingUid);
5746        synchronized (mPackages) {
5747            if (canViewInstantApps(callingUid, callingUserId)) {
5748                return new ArrayList<String>(mPackages.keySet());
5749            }
5750            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5751            final List<String> result = new ArrayList<>();
5752            if (instantAppPkgName != null) {
5753                // caller is an instant application; filter unexposed applications
5754                for (PackageParser.Package pkg : mPackages.values()) {
5755                    if (!pkg.visibleToInstantApps) {
5756                        continue;
5757                    }
5758                    result.add(pkg.packageName);
5759                }
5760            } else {
5761                // caller is a normal application; filter instant applications
5762                for (PackageParser.Package pkg : mPackages.values()) {
5763                    final PackageSetting ps =
5764                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5765                    if (ps != null
5766                            && ps.getInstantApp(callingUserId)
5767                            && !mInstantAppRegistry.isInstantAccessGranted(
5768                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5769                        continue;
5770                    }
5771                    result.add(pkg.packageName);
5772                }
5773            }
5774            return result;
5775        }
5776    }
5777
5778    @Override
5779    public String[] getPackagesForUid(int uid) {
5780        final int callingUid = Binder.getCallingUid();
5781        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5782        final int userId = UserHandle.getUserId(uid);
5783        uid = UserHandle.getAppId(uid);
5784        // reader
5785        synchronized (mPackages) {
5786            Object obj = mSettings.getUserIdLPr(uid);
5787            if (obj instanceof SharedUserSetting) {
5788                if (isCallerInstantApp) {
5789                    return null;
5790                }
5791                final SharedUserSetting sus = (SharedUserSetting) obj;
5792                final int N = sus.packages.size();
5793                String[] res = new String[N];
5794                final Iterator<PackageSetting> it = sus.packages.iterator();
5795                int i = 0;
5796                while (it.hasNext()) {
5797                    PackageSetting ps = it.next();
5798                    if (ps.getInstalled(userId)) {
5799                        res[i++] = ps.name;
5800                    } else {
5801                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5802                    }
5803                }
5804                return res;
5805            } else if (obj instanceof PackageSetting) {
5806                final PackageSetting ps = (PackageSetting) obj;
5807                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5808                    return new String[]{ps.name};
5809                }
5810            }
5811        }
5812        return null;
5813    }
5814
5815    @Override
5816    public String getNameForUid(int uid) {
5817        final int callingUid = Binder.getCallingUid();
5818        if (getInstantAppPackageName(callingUid) != null) {
5819            return null;
5820        }
5821        synchronized (mPackages) {
5822            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5823            if (obj instanceof SharedUserSetting) {
5824                final SharedUserSetting sus = (SharedUserSetting) obj;
5825                return sus.name + ":" + sus.userId;
5826            } else if (obj instanceof PackageSetting) {
5827                final PackageSetting ps = (PackageSetting) obj;
5828                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5829                    return null;
5830                }
5831                return ps.name;
5832            }
5833            return null;
5834        }
5835    }
5836
5837    @Override
5838    public String[] getNamesForUids(int[] uids) {
5839        if (uids == null || uids.length == 0) {
5840            return null;
5841        }
5842        final int callingUid = Binder.getCallingUid();
5843        if (getInstantAppPackageName(callingUid) != null) {
5844            return null;
5845        }
5846        final String[] names = new String[uids.length];
5847        synchronized (mPackages) {
5848            for (int i = uids.length - 1; i >= 0; i--) {
5849                final int uid = uids[i];
5850                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5851                if (obj instanceof SharedUserSetting) {
5852                    final SharedUserSetting sus = (SharedUserSetting) obj;
5853                    names[i] = "shared:" + sus.name;
5854                } else if (obj instanceof PackageSetting) {
5855                    final PackageSetting ps = (PackageSetting) obj;
5856                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5857                        names[i] = null;
5858                    } else {
5859                        names[i] = ps.name;
5860                    }
5861                } else {
5862                    names[i] = null;
5863                }
5864            }
5865        }
5866        return names;
5867    }
5868
5869    @Override
5870    public int getUidForSharedUser(String sharedUserName) {
5871        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5872            return -1;
5873        }
5874        if (sharedUserName == null) {
5875            return -1;
5876        }
5877        // reader
5878        synchronized (mPackages) {
5879            SharedUserSetting suid;
5880            try {
5881                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5882                if (suid != null) {
5883                    return suid.userId;
5884                }
5885            } catch (PackageManagerException ignore) {
5886                // can't happen, but, still need to catch it
5887            }
5888            return -1;
5889        }
5890    }
5891
5892    @Override
5893    public int getFlagsForUid(int uid) {
5894        final int callingUid = Binder.getCallingUid();
5895        if (getInstantAppPackageName(callingUid) != null) {
5896            return 0;
5897        }
5898        synchronized (mPackages) {
5899            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5900            if (obj instanceof SharedUserSetting) {
5901                final SharedUserSetting sus = (SharedUserSetting) obj;
5902                return sus.pkgFlags;
5903            } else if (obj instanceof PackageSetting) {
5904                final PackageSetting ps = (PackageSetting) obj;
5905                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5906                    return 0;
5907                }
5908                return ps.pkgFlags;
5909            }
5910        }
5911        return 0;
5912    }
5913
5914    @Override
5915    public int getPrivateFlagsForUid(int uid) {
5916        final int callingUid = Binder.getCallingUid();
5917        if (getInstantAppPackageName(callingUid) != null) {
5918            return 0;
5919        }
5920        synchronized (mPackages) {
5921            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5922            if (obj instanceof SharedUserSetting) {
5923                final SharedUserSetting sus = (SharedUserSetting) obj;
5924                return sus.pkgPrivateFlags;
5925            } else if (obj instanceof PackageSetting) {
5926                final PackageSetting ps = (PackageSetting) obj;
5927                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5928                    return 0;
5929                }
5930                return ps.pkgPrivateFlags;
5931            }
5932        }
5933        return 0;
5934    }
5935
5936    @Override
5937    public boolean isUidPrivileged(int uid) {
5938        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5939            return false;
5940        }
5941        uid = UserHandle.getAppId(uid);
5942        // reader
5943        synchronized (mPackages) {
5944            Object obj = mSettings.getUserIdLPr(uid);
5945            if (obj instanceof SharedUserSetting) {
5946                final SharedUserSetting sus = (SharedUserSetting) obj;
5947                final Iterator<PackageSetting> it = sus.packages.iterator();
5948                while (it.hasNext()) {
5949                    if (it.next().isPrivileged()) {
5950                        return true;
5951                    }
5952                }
5953            } else if (obj instanceof PackageSetting) {
5954                final PackageSetting ps = (PackageSetting) obj;
5955                return ps.isPrivileged();
5956            }
5957        }
5958        return false;
5959    }
5960
5961    @Override
5962    public String[] getAppOpPermissionPackages(String permName) {
5963        return mPermissionManager.getAppOpPermissionPackages(permName);
5964    }
5965
5966    @Override
5967    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5968            int flags, int userId) {
5969        return resolveIntentInternal(intent, resolvedType, flags, userId, false,
5970                Binder.getCallingUid());
5971    }
5972
5973    /**
5974     * Normally instant apps can only be resolved when they're visible to the caller.
5975     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5976     * since we need to allow the system to start any installed application.
5977     */
5978    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5979            int flags, int userId, boolean resolveForStart, int filterCallingUid) {
5980        try {
5981            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5982
5983            if (!sUserManager.exists(userId)) return null;
5984            final int callingUid = Binder.getCallingUid();
5985            flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart);
5986            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5987                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5988
5989            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5990            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5991                    flags, filterCallingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5992            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5993
5994            final ResolveInfo bestChoice =
5995                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5996            return bestChoice;
5997        } finally {
5998            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5999        }
6000    }
6001
6002    @Override
6003    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6004        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6005            throw new SecurityException(
6006                    "findPersistentPreferredActivity can only be run by the system");
6007        }
6008        if (!sUserManager.exists(userId)) {
6009            return null;
6010        }
6011        final int callingUid = Binder.getCallingUid();
6012        intent = updateIntentForResolve(intent);
6013        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6014        final int flags = updateFlagsForResolve(
6015                0, userId, intent, callingUid, false /*includeInstantApps*/);
6016        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6017                userId);
6018        synchronized (mPackages) {
6019            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6020                    userId);
6021        }
6022    }
6023
6024    @Override
6025    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6026            IntentFilter filter, int match, ComponentName activity) {
6027        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6028            return;
6029        }
6030        final int userId = UserHandle.getCallingUserId();
6031        if (DEBUG_PREFERRED) {
6032            Log.v(TAG, "setLastChosenActivity intent=" + intent
6033                + " resolvedType=" + resolvedType
6034                + " flags=" + flags
6035                + " filter=" + filter
6036                + " match=" + match
6037                + " activity=" + activity);
6038            filter.dump(new PrintStreamPrinter(System.out), "    ");
6039        }
6040        intent.setComponent(null);
6041        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6042                userId);
6043        // Find any earlier preferred or last chosen entries and nuke them
6044        findPreferredActivity(intent, resolvedType,
6045                flags, query, 0, false, true, false, userId);
6046        // Add the new activity as the last chosen for this filter
6047        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6048                "Setting last chosen");
6049    }
6050
6051    @Override
6052    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6053        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6054            return null;
6055        }
6056        final int userId = UserHandle.getCallingUserId();
6057        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6058        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6059                userId);
6060        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6061                false, false, false, userId);
6062    }
6063
6064    /**
6065     * Returns whether or not instant apps have been disabled remotely.
6066     */
6067    private boolean areWebInstantAppsDisabled() {
6068        return mWebInstantAppsDisabled;
6069    }
6070
6071    private boolean isInstantAppResolutionAllowed(
6072            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6073            boolean skipPackageCheck) {
6074        if (mInstantAppResolverConnection == null) {
6075            return false;
6076        }
6077        if (mInstantAppInstallerActivity == null) {
6078            return false;
6079        }
6080        if (intent.getComponent() != null) {
6081            return false;
6082        }
6083        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6084            return false;
6085        }
6086        if (!skipPackageCheck && intent.getPackage() != null) {
6087            return false;
6088        }
6089        if (!intent.isWebIntent()) {
6090            // for non web intents, we should not resolve externally if an app already exists to
6091            // handle it or if the caller didn't explicitly request it.
6092            if ((resolvedActivities != null && resolvedActivities.size() != 0)
6093                    || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) {
6094                return false;
6095            }
6096        } else {
6097            if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) {
6098                return false;
6099            } else if (areWebInstantAppsDisabled()) {
6100                return false;
6101            }
6102        }
6103        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6104        // Or if there's already an ephemeral app installed that handles the action
6105        synchronized (mPackages) {
6106            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6107            for (int n = 0; n < count; n++) {
6108                final ResolveInfo info = resolvedActivities.get(n);
6109                final String packageName = info.activityInfo.packageName;
6110                final PackageSetting ps = mSettings.mPackages.get(packageName);
6111                if (ps != null) {
6112                    // only check domain verification status if the app is not a browser
6113                    if (!info.handleAllWebDataURI) {
6114                        // Try to get the status from User settings first
6115                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6116                        final int status = (int) (packedStatus >> 32);
6117                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6118                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6119                            if (DEBUG_INSTANT) {
6120                                Slog.v(TAG, "DENY instant app;"
6121                                    + " pkg: " + packageName + ", status: " + status);
6122                            }
6123                            return false;
6124                        }
6125                    }
6126                    if (ps.getInstantApp(userId)) {
6127                        if (DEBUG_INSTANT) {
6128                            Slog.v(TAG, "DENY instant app installed;"
6129                                    + " pkg: " + packageName);
6130                        }
6131                        return false;
6132                    }
6133                }
6134            }
6135        }
6136        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6137        return true;
6138    }
6139
6140    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6141            Intent origIntent, String resolvedType, String callingPackage,
6142            Bundle verificationBundle, int userId) {
6143        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6144                new InstantAppRequest(responseObj, origIntent, resolvedType,
6145                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6146        mHandler.sendMessage(msg);
6147    }
6148
6149    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6150            int flags, List<ResolveInfo> query, int userId) {
6151        if (query != null) {
6152            final int N = query.size();
6153            if (N == 1) {
6154                return query.get(0);
6155            } else if (N > 1) {
6156                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6157                // If there is more than one activity with the same priority,
6158                // then let the user decide between them.
6159                ResolveInfo r0 = query.get(0);
6160                ResolveInfo r1 = query.get(1);
6161                if (DEBUG_INTENT_MATCHING || debug) {
6162                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6163                            + r1.activityInfo.name + "=" + r1.priority);
6164                }
6165                // If the first activity has a higher priority, or a different
6166                // default, then it is always desirable to pick it.
6167                if (r0.priority != r1.priority
6168                        || r0.preferredOrder != r1.preferredOrder
6169                        || r0.isDefault != r1.isDefault) {
6170                    return query.get(0);
6171                }
6172                // If we have saved a preference for a preferred activity for
6173                // this Intent, use that.
6174                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6175                        flags, query, r0.priority, true, false, debug, userId);
6176                if (ri != null) {
6177                    return ri;
6178                }
6179                // If we have an ephemeral app, use it
6180                for (int i = 0; i < N; i++) {
6181                    ri = query.get(i);
6182                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6183                        final String packageName = ri.activityInfo.packageName;
6184                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6185                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6186                        final int status = (int)(packedStatus >> 32);
6187                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6188                            return ri;
6189                        }
6190                    }
6191                }
6192                ri = new ResolveInfo(mResolveInfo);
6193                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6194                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6195                // If all of the options come from the same package, show the application's
6196                // label and icon instead of the generic resolver's.
6197                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6198                // and then throw away the ResolveInfo itself, meaning that the caller loses
6199                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6200                // a fallback for this case; we only set the target package's resources on
6201                // the ResolveInfo, not the ActivityInfo.
6202                final String intentPackage = intent.getPackage();
6203                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6204                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6205                    ri.resolvePackageName = intentPackage;
6206                    if (userNeedsBadging(userId)) {
6207                        ri.noResourceId = true;
6208                    } else {
6209                        ri.icon = appi.icon;
6210                    }
6211                    ri.iconResourceId = appi.icon;
6212                    ri.labelRes = appi.labelRes;
6213                }
6214                ri.activityInfo.applicationInfo = new ApplicationInfo(
6215                        ri.activityInfo.applicationInfo);
6216                if (userId != 0) {
6217                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6218                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6219                }
6220                // Make sure that the resolver is displayable in car mode
6221                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6222                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6223                return ri;
6224            }
6225        }
6226        return null;
6227    }
6228
6229    /**
6230     * Return true if the given list is not empty and all of its contents have
6231     * an activityInfo with the given package name.
6232     */
6233    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6234        if (ArrayUtils.isEmpty(list)) {
6235            return false;
6236        }
6237        for (int i = 0, N = list.size(); i < N; i++) {
6238            final ResolveInfo ri = list.get(i);
6239            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6240            if (ai == null || !packageName.equals(ai.packageName)) {
6241                return false;
6242            }
6243        }
6244        return true;
6245    }
6246
6247    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6248            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6249        final int N = query.size();
6250        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6251                .get(userId);
6252        // Get the list of persistent preferred activities that handle the intent
6253        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6254        List<PersistentPreferredActivity> pprefs = ppir != null
6255                ? ppir.queryIntent(intent, resolvedType,
6256                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6257                        userId)
6258                : null;
6259        if (pprefs != null && pprefs.size() > 0) {
6260            final int M = pprefs.size();
6261            for (int i=0; i<M; i++) {
6262                final PersistentPreferredActivity ppa = pprefs.get(i);
6263                if (DEBUG_PREFERRED || debug) {
6264                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6265                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6266                            + "\n  component=" + ppa.mComponent);
6267                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6268                }
6269                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6270                        flags | MATCH_DISABLED_COMPONENTS, userId);
6271                if (DEBUG_PREFERRED || debug) {
6272                    Slog.v(TAG, "Found persistent preferred activity:");
6273                    if (ai != null) {
6274                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6275                    } else {
6276                        Slog.v(TAG, "  null");
6277                    }
6278                }
6279                if (ai == null) {
6280                    // This previously registered persistent preferred activity
6281                    // component is no longer known. Ignore it and do NOT remove it.
6282                    continue;
6283                }
6284                for (int j=0; j<N; j++) {
6285                    final ResolveInfo ri = query.get(j);
6286                    if (!ri.activityInfo.applicationInfo.packageName
6287                            .equals(ai.applicationInfo.packageName)) {
6288                        continue;
6289                    }
6290                    if (!ri.activityInfo.name.equals(ai.name)) {
6291                        continue;
6292                    }
6293                    //  Found a persistent preference that can handle the intent.
6294                    if (DEBUG_PREFERRED || debug) {
6295                        Slog.v(TAG, "Returning persistent preferred activity: " +
6296                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6297                    }
6298                    return ri;
6299                }
6300            }
6301        }
6302        return null;
6303    }
6304
6305    // TODO: handle preferred activities missing while user has amnesia
6306    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6307            List<ResolveInfo> query, int priority, boolean always,
6308            boolean removeMatches, boolean debug, int userId) {
6309        if (!sUserManager.exists(userId)) return null;
6310        final int callingUid = Binder.getCallingUid();
6311        flags = updateFlagsForResolve(
6312                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6313        intent = updateIntentForResolve(intent);
6314        // writer
6315        synchronized (mPackages) {
6316            // Try to find a matching persistent preferred activity.
6317            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6318                    debug, userId);
6319
6320            // If a persistent preferred activity matched, use it.
6321            if (pri != null) {
6322                return pri;
6323            }
6324
6325            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6326            // Get the list of preferred activities that handle the intent
6327            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6328            List<PreferredActivity> prefs = pir != null
6329                    ? pir.queryIntent(intent, resolvedType,
6330                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6331                            userId)
6332                    : null;
6333            if (prefs != null && prefs.size() > 0) {
6334                boolean changed = false;
6335                try {
6336                    // First figure out how good the original match set is.
6337                    // We will only allow preferred activities that came
6338                    // from the same match quality.
6339                    int match = 0;
6340
6341                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6342
6343                    final int N = query.size();
6344                    for (int j=0; j<N; j++) {
6345                        final ResolveInfo ri = query.get(j);
6346                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6347                                + ": 0x" + Integer.toHexString(match));
6348                        if (ri.match > match) {
6349                            match = ri.match;
6350                        }
6351                    }
6352
6353                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6354                            + Integer.toHexString(match));
6355
6356                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6357                    final int M = prefs.size();
6358                    for (int i=0; i<M; i++) {
6359                        final PreferredActivity pa = prefs.get(i);
6360                        if (DEBUG_PREFERRED || debug) {
6361                            Slog.v(TAG, "Checking PreferredActivity ds="
6362                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6363                                    + "\n  component=" + pa.mPref.mComponent);
6364                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6365                        }
6366                        if (pa.mPref.mMatch != match) {
6367                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6368                                    + Integer.toHexString(pa.mPref.mMatch));
6369                            continue;
6370                        }
6371                        // If it's not an "always" type preferred activity and that's what we're
6372                        // looking for, skip it.
6373                        if (always && !pa.mPref.mAlways) {
6374                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6375                            continue;
6376                        }
6377                        final ActivityInfo ai = getActivityInfo(
6378                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6379                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6380                                userId);
6381                        if (DEBUG_PREFERRED || debug) {
6382                            Slog.v(TAG, "Found preferred activity:");
6383                            if (ai != null) {
6384                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6385                            } else {
6386                                Slog.v(TAG, "  null");
6387                            }
6388                        }
6389                        if (ai == null) {
6390                            // This previously registered preferred activity
6391                            // component is no longer known.  Most likely an update
6392                            // to the app was installed and in the new version this
6393                            // component no longer exists.  Clean it up by removing
6394                            // it from the preferred activities list, and skip it.
6395                            Slog.w(TAG, "Removing dangling preferred activity: "
6396                                    + pa.mPref.mComponent);
6397                            pir.removeFilter(pa);
6398                            changed = true;
6399                            continue;
6400                        }
6401                        for (int j=0; j<N; j++) {
6402                            final ResolveInfo ri = query.get(j);
6403                            if (!ri.activityInfo.applicationInfo.packageName
6404                                    .equals(ai.applicationInfo.packageName)) {
6405                                continue;
6406                            }
6407                            if (!ri.activityInfo.name.equals(ai.name)) {
6408                                continue;
6409                            }
6410
6411                            if (removeMatches) {
6412                                pir.removeFilter(pa);
6413                                changed = true;
6414                                if (DEBUG_PREFERRED) {
6415                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6416                                }
6417                                break;
6418                            }
6419
6420                            // Okay we found a previously set preferred or last chosen app.
6421                            // If the result set is different from when this
6422                            // was created, and is not a subset of the preferred set, we need to
6423                            // clear it and re-ask the user their preference, if we're looking for
6424                            // an "always" type entry.
6425                            if (always && !pa.mPref.sameSet(query)) {
6426                                if (pa.mPref.isSuperset(query)) {
6427                                    // some components of the set are no longer present in
6428                                    // the query, but the preferred activity can still be reused
6429                                    if (DEBUG_PREFERRED) {
6430                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6431                                                + " still valid as only non-preferred components"
6432                                                + " were removed for " + intent + " type "
6433                                                + resolvedType);
6434                                    }
6435                                    // remove obsolete components and re-add the up-to-date filter
6436                                    PreferredActivity freshPa = new PreferredActivity(pa,
6437                                            pa.mPref.mMatch,
6438                                            pa.mPref.discardObsoleteComponents(query),
6439                                            pa.mPref.mComponent,
6440                                            pa.mPref.mAlways);
6441                                    pir.removeFilter(pa);
6442                                    pir.addFilter(freshPa);
6443                                    changed = true;
6444                                } else {
6445                                    Slog.i(TAG,
6446                                            "Result set changed, dropping preferred activity for "
6447                                                    + intent + " type " + resolvedType);
6448                                    if (DEBUG_PREFERRED) {
6449                                        Slog.v(TAG, "Removing preferred activity since set changed "
6450                                                + pa.mPref.mComponent);
6451                                    }
6452                                    pir.removeFilter(pa);
6453                                    // Re-add the filter as a "last chosen" entry (!always)
6454                                    PreferredActivity lastChosen = new PreferredActivity(
6455                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6456                                    pir.addFilter(lastChosen);
6457                                    changed = true;
6458                                    return null;
6459                                }
6460                            }
6461
6462                            // Yay! Either the set matched or we're looking for the last chosen
6463                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6464                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6465                            return ri;
6466                        }
6467                    }
6468                } finally {
6469                    if (changed) {
6470                        if (DEBUG_PREFERRED) {
6471                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6472                        }
6473                        scheduleWritePackageRestrictionsLocked(userId);
6474                    }
6475                }
6476            }
6477        }
6478        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6479        return null;
6480    }
6481
6482    /*
6483     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6484     */
6485    @Override
6486    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6487            int targetUserId) {
6488        mContext.enforceCallingOrSelfPermission(
6489                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6490        List<CrossProfileIntentFilter> matches =
6491                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6492        if (matches != null) {
6493            int size = matches.size();
6494            for (int i = 0; i < size; i++) {
6495                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6496            }
6497        }
6498        if (intent.hasWebURI()) {
6499            // cross-profile app linking works only towards the parent.
6500            final int callingUid = Binder.getCallingUid();
6501            final UserInfo parent = getProfileParent(sourceUserId);
6502            synchronized(mPackages) {
6503                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6504                        false /*includeInstantApps*/);
6505                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6506                        intent, resolvedType, flags, sourceUserId, parent.id);
6507                return xpDomainInfo != null;
6508            }
6509        }
6510        return false;
6511    }
6512
6513    private UserInfo getProfileParent(int userId) {
6514        final long identity = Binder.clearCallingIdentity();
6515        try {
6516            return sUserManager.getProfileParent(userId);
6517        } finally {
6518            Binder.restoreCallingIdentity(identity);
6519        }
6520    }
6521
6522    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6523            String resolvedType, int userId) {
6524        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6525        if (resolver != null) {
6526            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6527        }
6528        return null;
6529    }
6530
6531    @Override
6532    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6533            String resolvedType, int flags, int userId) {
6534        try {
6535            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6536
6537            return new ParceledListSlice<>(
6538                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6539        } finally {
6540            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6541        }
6542    }
6543
6544    /**
6545     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6546     * instant, returns {@code null}.
6547     */
6548    private String getInstantAppPackageName(int callingUid) {
6549        synchronized (mPackages) {
6550            // If the caller is an isolated app use the owner's uid for the lookup.
6551            if (Process.isIsolated(callingUid)) {
6552                callingUid = mIsolatedOwners.get(callingUid);
6553            }
6554            final int appId = UserHandle.getAppId(callingUid);
6555            final Object obj = mSettings.getUserIdLPr(appId);
6556            if (obj instanceof PackageSetting) {
6557                final PackageSetting ps = (PackageSetting) obj;
6558                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6559                return isInstantApp ? ps.pkg.packageName : null;
6560            }
6561        }
6562        return null;
6563    }
6564
6565    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6566            String resolvedType, int flags, int userId) {
6567        return queryIntentActivitiesInternal(
6568                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6569                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6570    }
6571
6572    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6573            String resolvedType, int flags, int filterCallingUid, int userId,
6574            boolean resolveForStart, boolean allowDynamicSplits) {
6575        if (!sUserManager.exists(userId)) return Collections.emptyList();
6576        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6577        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6578                false /* requireFullPermission */, false /* checkShell */,
6579                "query intent activities");
6580        final String pkgName = intent.getPackage();
6581        ComponentName comp = intent.getComponent();
6582        if (comp == null) {
6583            if (intent.getSelector() != null) {
6584                intent = intent.getSelector();
6585                comp = intent.getComponent();
6586            }
6587        }
6588
6589        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6590                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6591        if (comp != null) {
6592            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6593            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6594            if (ai != null) {
6595                // When specifying an explicit component, we prevent the activity from being
6596                // used when either 1) the calling package is normal and the activity is within
6597                // an ephemeral application or 2) the calling package is ephemeral and the
6598                // activity is not visible to ephemeral applications.
6599                final boolean matchInstantApp =
6600                        (flags & PackageManager.MATCH_INSTANT) != 0;
6601                final boolean matchVisibleToInstantAppOnly =
6602                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6603                final boolean matchExplicitlyVisibleOnly =
6604                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6605                final boolean isCallerInstantApp =
6606                        instantAppPkgName != null;
6607                final boolean isTargetSameInstantApp =
6608                        comp.getPackageName().equals(instantAppPkgName);
6609                final boolean isTargetInstantApp =
6610                        (ai.applicationInfo.privateFlags
6611                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6612                final boolean isTargetVisibleToInstantApp =
6613                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6614                final boolean isTargetExplicitlyVisibleToInstantApp =
6615                        isTargetVisibleToInstantApp
6616                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6617                final boolean isTargetHiddenFromInstantApp =
6618                        !isTargetVisibleToInstantApp
6619                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6620                final boolean blockResolution =
6621                        !isTargetSameInstantApp
6622                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6623                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6624                                        && isTargetHiddenFromInstantApp));
6625                if (!blockResolution) {
6626                    final ResolveInfo ri = new ResolveInfo();
6627                    ri.activityInfo = ai;
6628                    list.add(ri);
6629                }
6630            }
6631            return applyPostResolutionFilter(
6632                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6633        }
6634
6635        // reader
6636        boolean sortResult = false;
6637        boolean addInstant = false;
6638        List<ResolveInfo> result;
6639        synchronized (mPackages) {
6640            if (pkgName == null) {
6641                List<CrossProfileIntentFilter> matchingFilters =
6642                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6643                // Check for results that need to skip the current profile.
6644                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6645                        resolvedType, flags, userId);
6646                if (xpResolveInfo != null) {
6647                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6648                    xpResult.add(xpResolveInfo);
6649                    return applyPostResolutionFilter(
6650                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6651                            allowDynamicSplits, filterCallingUid, userId, intent);
6652                }
6653
6654                // Check for results in the current profile.
6655                result = filterIfNotSystemUser(mActivities.queryIntent(
6656                        intent, resolvedType, flags, userId), userId);
6657                addInstant = isInstantAppResolutionAllowed(intent, result, userId,
6658                        false /*skipPackageCheck*/);
6659                // Check for cross profile results.
6660                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6661                xpResolveInfo = queryCrossProfileIntents(
6662                        matchingFilters, intent, resolvedType, flags, userId,
6663                        hasNonNegativePriorityResult);
6664                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6665                    boolean isVisibleToUser = filterIfNotSystemUser(
6666                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6667                    if (isVisibleToUser) {
6668                        result.add(xpResolveInfo);
6669                        sortResult = true;
6670                    }
6671                }
6672                if (intent.hasWebURI()) {
6673                    CrossProfileDomainInfo xpDomainInfo = null;
6674                    final UserInfo parent = getProfileParent(userId);
6675                    if (parent != null) {
6676                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6677                                flags, userId, parent.id);
6678                    }
6679                    if (xpDomainInfo != null) {
6680                        if (xpResolveInfo != null) {
6681                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6682                            // in the result.
6683                            result.remove(xpResolveInfo);
6684                        }
6685                        if (result.size() == 0 && !addInstant) {
6686                            // No result in current profile, but found candidate in parent user.
6687                            // And we are not going to add emphemeral app, so we can return the
6688                            // result straight away.
6689                            result.add(xpDomainInfo.resolveInfo);
6690                            return applyPostResolutionFilter(result, instantAppPkgName,
6691                                    allowDynamicSplits, filterCallingUid, userId, intent);
6692                        }
6693                    } else if (result.size() <= 1 && !addInstant) {
6694                        // No result in parent user and <= 1 result in current profile, and we
6695                        // are not going to add emphemeral app, so we can return the result without
6696                        // further processing.
6697                        return applyPostResolutionFilter(result, instantAppPkgName,
6698                                allowDynamicSplits, filterCallingUid, userId, intent);
6699                    }
6700                    // We have more than one candidate (combining results from current and parent
6701                    // profile), so we need filtering and sorting.
6702                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6703                            intent, flags, result, xpDomainInfo, userId);
6704                    sortResult = true;
6705                }
6706            } else {
6707                final PackageParser.Package pkg = mPackages.get(pkgName);
6708                result = null;
6709                if (pkg != null) {
6710                    result = filterIfNotSystemUser(
6711                            mActivities.queryIntentForPackage(
6712                                    intent, resolvedType, flags, pkg.activities, userId),
6713                            userId);
6714                }
6715                if (result == null || result.size() == 0) {
6716                    // the caller wants to resolve for a particular package; however, there
6717                    // were no installed results, so, try to find an ephemeral result
6718                    addInstant = isInstantAppResolutionAllowed(
6719                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6720                    if (result == null) {
6721                        result = new ArrayList<>();
6722                    }
6723                }
6724            }
6725        }
6726        if (addInstant) {
6727            result = maybeAddInstantAppInstaller(
6728                    result, intent, resolvedType, flags, userId, resolveForStart);
6729        }
6730        if (sortResult) {
6731            Collections.sort(result, mResolvePrioritySorter);
6732        }
6733        return applyPostResolutionFilter(
6734                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6735    }
6736
6737    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6738            String resolvedType, int flags, int userId, boolean resolveForStart) {
6739        // first, check to see if we've got an instant app already installed
6740        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6741        ResolveInfo localInstantApp = null;
6742        boolean blockResolution = false;
6743        if (!alreadyResolvedLocally) {
6744            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6745                    flags
6746                        | PackageManager.GET_RESOLVED_FILTER
6747                        | PackageManager.MATCH_INSTANT
6748                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6749                    userId);
6750            for (int i = instantApps.size() - 1; i >= 0; --i) {
6751                final ResolveInfo info = instantApps.get(i);
6752                final String packageName = info.activityInfo.packageName;
6753                final PackageSetting ps = mSettings.mPackages.get(packageName);
6754                if (ps.getInstantApp(userId)) {
6755                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6756                    final int status = (int)(packedStatus >> 32);
6757                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6758                        // there's a local instant application installed, but, the user has
6759                        // chosen to never use it; skip resolution and don't acknowledge
6760                        // an instant application is even available
6761                        if (DEBUG_INSTANT) {
6762                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6763                        }
6764                        blockResolution = true;
6765                        break;
6766                    } else {
6767                        // we have a locally installed instant application; skip resolution
6768                        // but acknowledge there's an instant application available
6769                        if (DEBUG_INSTANT) {
6770                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6771                        }
6772                        localInstantApp = info;
6773                        break;
6774                    }
6775                }
6776            }
6777        }
6778        // no app installed, let's see if one's available
6779        AuxiliaryResolveInfo auxiliaryResponse = null;
6780        if (!blockResolution) {
6781            if (localInstantApp == null) {
6782                // we don't have an instant app locally, resolve externally
6783                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6784                final InstantAppRequest requestObject = new InstantAppRequest(
6785                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6786                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6787                        resolveForStart);
6788                auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne(
6789                        mInstantAppResolverConnection, requestObject);
6790                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6791            } else {
6792                // we have an instant application locally, but, we can't admit that since
6793                // callers shouldn't be able to determine prior browsing. create a dummy
6794                // auxiliary response so the downstream code behaves as if there's an
6795                // instant application available externally. when it comes time to start
6796                // the instant application, we'll do the right thing.
6797                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6798                auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */,
6799                                        ai.packageName, ai.longVersionCode, null /* splitName */);
6800            }
6801        }
6802        if (intent.isWebIntent() && auxiliaryResponse == null) {
6803            return result;
6804        }
6805        final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6806        if (ps == null
6807                || ps.getUserState().get(userId) == null
6808                || !ps.getUserState().get(userId).isEnabled(mInstantAppInstallerActivity, 0)) {
6809            return result;
6810        }
6811        final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6812        ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6813                mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6814        ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6815                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6816        // add a non-generic filter
6817        ephemeralInstaller.filter = new IntentFilter();
6818        if (intent.getAction() != null) {
6819            ephemeralInstaller.filter.addAction(intent.getAction());
6820        }
6821        if (intent.getData() != null && intent.getData().getPath() != null) {
6822            ephemeralInstaller.filter.addDataPath(
6823                    intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6824        }
6825        ephemeralInstaller.isInstantAppAvailable = true;
6826        // make sure this resolver is the default
6827        ephemeralInstaller.isDefault = true;
6828        ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6829        if (DEBUG_INSTANT) {
6830            Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6831        }
6832
6833        result.add(ephemeralInstaller);
6834        return result;
6835    }
6836
6837    private static class CrossProfileDomainInfo {
6838        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6839        ResolveInfo resolveInfo;
6840        /* Best domain verification status of the activities found in the other profile */
6841        int bestDomainVerificationStatus;
6842    }
6843
6844    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6845            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6846        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6847                sourceUserId)) {
6848            return null;
6849        }
6850        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6851                resolvedType, flags, parentUserId);
6852
6853        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6854            return null;
6855        }
6856        CrossProfileDomainInfo result = null;
6857        int size = resultTargetUser.size();
6858        for (int i = 0; i < size; i++) {
6859            ResolveInfo riTargetUser = resultTargetUser.get(i);
6860            // Intent filter verification is only for filters that specify a host. So don't return
6861            // those that handle all web uris.
6862            if (riTargetUser.handleAllWebDataURI) {
6863                continue;
6864            }
6865            String packageName = riTargetUser.activityInfo.packageName;
6866            PackageSetting ps = mSettings.mPackages.get(packageName);
6867            if (ps == null) {
6868                continue;
6869            }
6870            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6871            int status = (int)(verificationState >> 32);
6872            if (result == null) {
6873                result = new CrossProfileDomainInfo();
6874                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6875                        sourceUserId, parentUserId);
6876                result.bestDomainVerificationStatus = status;
6877            } else {
6878                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6879                        result.bestDomainVerificationStatus);
6880            }
6881        }
6882        // Don't consider matches with status NEVER across profiles.
6883        if (result != null && result.bestDomainVerificationStatus
6884                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6885            return null;
6886        }
6887        return result;
6888    }
6889
6890    /**
6891     * Verification statuses are ordered from the worse to the best, except for
6892     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6893     */
6894    private int bestDomainVerificationStatus(int status1, int status2) {
6895        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6896            return status2;
6897        }
6898        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6899            return status1;
6900        }
6901        return (int) MathUtils.max(status1, status2);
6902    }
6903
6904    private boolean isUserEnabled(int userId) {
6905        long callingId = Binder.clearCallingIdentity();
6906        try {
6907            UserInfo userInfo = sUserManager.getUserInfo(userId);
6908            return userInfo != null && userInfo.isEnabled();
6909        } finally {
6910            Binder.restoreCallingIdentity(callingId);
6911        }
6912    }
6913
6914    /**
6915     * Filter out activities with systemUserOnly flag set, when current user is not System.
6916     *
6917     * @return filtered list
6918     */
6919    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6920        if (userId == UserHandle.USER_SYSTEM) {
6921            return resolveInfos;
6922        }
6923        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6924            ResolveInfo info = resolveInfos.get(i);
6925            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6926                resolveInfos.remove(i);
6927            }
6928        }
6929        return resolveInfos;
6930    }
6931
6932    /**
6933     * Filters out ephemeral activities.
6934     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6935     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6936     *
6937     * @param resolveInfos The pre-filtered list of resolved activities
6938     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6939     *          is performed.
6940     * @param intent
6941     * @return A filtered list of resolved activities.
6942     */
6943    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6944            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId,
6945            Intent intent) {
6946        final boolean blockInstant = intent.isWebIntent() && areWebInstantAppsDisabled();
6947        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6948            final ResolveInfo info = resolveInfos.get(i);
6949            // remove locally resolved instant app web results when disabled
6950            if (info.isInstantAppAvailable && blockInstant) {
6951                resolveInfos.remove(i);
6952                continue;
6953            }
6954            // allow activities that are defined in the provided package
6955            if (allowDynamicSplits
6956                    && info.activityInfo != null
6957                    && info.activityInfo.splitName != null
6958                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6959                            info.activityInfo.splitName)) {
6960                if (mInstantAppInstallerActivity == null) {
6961                    if (DEBUG_INSTALL) {
6962                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6963                    }
6964                    resolveInfos.remove(i);
6965                    continue;
6966                }
6967                if (blockInstant && isInstantApp(info.activityInfo.packageName, userId)) {
6968                    resolveInfos.remove(i);
6969                    continue;
6970                }
6971                // requested activity is defined in a split that hasn't been installed yet.
6972                // add the installer to the resolve list
6973                if (DEBUG_INSTALL) {
6974                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6975                }
6976                final ResolveInfo installerInfo = new ResolveInfo(
6977                        mInstantAppInstallerInfo);
6978                final ComponentName installFailureActivity = findInstallFailureActivity(
6979                        info.activityInfo.packageName,  filterCallingUid, userId);
6980                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6981                        installFailureActivity,
6982                        info.activityInfo.packageName,
6983                        info.activityInfo.applicationInfo.longVersionCode,
6984                        info.activityInfo.splitName);
6985                // add a non-generic filter
6986                installerInfo.filter = new IntentFilter();
6987
6988                // This resolve info may appear in the chooser UI, so let us make it
6989                // look as the one it replaces as far as the user is concerned which
6990                // requires loading the correct label and icon for the resolve info.
6991                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6992                installerInfo.labelRes = info.resolveLabelResId();
6993                installerInfo.icon = info.resolveIconResId();
6994                installerInfo.isInstantAppAvailable = true;
6995                resolveInfos.set(i, installerInfo);
6996                continue;
6997            }
6998            // caller is a full app, don't need to apply any other filtering
6999            if (ephemeralPkgName == null) {
7000                continue;
7001            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7002                // caller is same app; don't need to apply any other filtering
7003                continue;
7004            }
7005            // allow activities that have been explicitly exposed to ephemeral apps
7006            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7007            if (!isEphemeralApp
7008                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7009                continue;
7010            }
7011            resolveInfos.remove(i);
7012        }
7013        return resolveInfos;
7014    }
7015
7016    /**
7017     * Returns the activity component that can handle install failures.
7018     * <p>By default, the instant application installer handles failures. However, an
7019     * application may want to handle failures on its own. Applications do this by
7020     * creating an activity with an intent filter that handles the action
7021     * {@link Intent#ACTION_INSTALL_FAILURE}.
7022     */
7023    private @Nullable ComponentName findInstallFailureActivity(
7024            String packageName, int filterCallingUid, int userId) {
7025        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
7026        failureActivityIntent.setPackage(packageName);
7027        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
7028        final List<ResolveInfo> result = queryIntentActivitiesInternal(
7029                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
7030                false /*resolveForStart*/, false /*allowDynamicSplits*/);
7031        final int NR = result.size();
7032        if (NR > 0) {
7033            for (int i = 0; i < NR; i++) {
7034                final ResolveInfo info = result.get(i);
7035                if (info.activityInfo.splitName != null) {
7036                    continue;
7037                }
7038                return new ComponentName(packageName, info.activityInfo.name);
7039            }
7040        }
7041        return null;
7042    }
7043
7044    /**
7045     * @param resolveInfos list of resolve infos in descending priority order
7046     * @return if the list contains a resolve info with non-negative priority
7047     */
7048    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7049        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7050    }
7051
7052    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7053            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7054            int userId) {
7055        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7056
7057        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7058            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7059                    candidates.size());
7060        }
7061
7062        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7063        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7064        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7065        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7066        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7067        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7068
7069        synchronized (mPackages) {
7070            final int count = candidates.size();
7071            // First, try to use linked apps. Partition the candidates into four lists:
7072            // one for the final results, one for the "do not use ever", one for "undefined status"
7073            // and finally one for "browser app type".
7074            for (int n=0; n<count; n++) {
7075                ResolveInfo info = candidates.get(n);
7076                String packageName = info.activityInfo.packageName;
7077                PackageSetting ps = mSettings.mPackages.get(packageName);
7078                if (ps != null) {
7079                    // Add to the special match all list (Browser use case)
7080                    if (info.handleAllWebDataURI) {
7081                        matchAllList.add(info);
7082                        continue;
7083                    }
7084                    // Try to get the status from User settings first
7085                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7086                    int status = (int)(packedStatus >> 32);
7087                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7088                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7089                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7090                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7091                                    + " : linkgen=" + linkGeneration);
7092                        }
7093                        // Use link-enabled generation as preferredOrder, i.e.
7094                        // prefer newly-enabled over earlier-enabled.
7095                        info.preferredOrder = linkGeneration;
7096                        alwaysList.add(info);
7097                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7098                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7099                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7100                        }
7101                        neverList.add(info);
7102                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7103                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7104                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7105                        }
7106                        alwaysAskList.add(info);
7107                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7108                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7109                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7110                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7111                        }
7112                        undefinedList.add(info);
7113                    }
7114                }
7115            }
7116
7117            // We'll want to include browser possibilities in a few cases
7118            boolean includeBrowser = false;
7119
7120            // First try to add the "always" resolution(s) for the current user, if any
7121            if (alwaysList.size() > 0) {
7122                result.addAll(alwaysList);
7123            } else {
7124                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7125                result.addAll(undefinedList);
7126                // Maybe add one for the other profile.
7127                if (xpDomainInfo != null && (
7128                        xpDomainInfo.bestDomainVerificationStatus
7129                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7130                    result.add(xpDomainInfo.resolveInfo);
7131                }
7132                includeBrowser = true;
7133            }
7134
7135            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7136            // If there were 'always' entries their preferred order has been set, so we also
7137            // back that off to make the alternatives equivalent
7138            if (alwaysAskList.size() > 0) {
7139                for (ResolveInfo i : result) {
7140                    i.preferredOrder = 0;
7141                }
7142                result.addAll(alwaysAskList);
7143                includeBrowser = true;
7144            }
7145
7146            if (includeBrowser) {
7147                // Also add browsers (all of them or only the default one)
7148                if (DEBUG_DOMAIN_VERIFICATION) {
7149                    Slog.v(TAG, "   ...including browsers in candidate set");
7150                }
7151                if ((matchFlags & MATCH_ALL) != 0) {
7152                    result.addAll(matchAllList);
7153                } else {
7154                    // Browser/generic handling case.  If there's a default browser, go straight
7155                    // to that (but only if there is no other higher-priority match).
7156                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7157                    int maxMatchPrio = 0;
7158                    ResolveInfo defaultBrowserMatch = null;
7159                    final int numCandidates = matchAllList.size();
7160                    for (int n = 0; n < numCandidates; n++) {
7161                        ResolveInfo info = matchAllList.get(n);
7162                        // track the highest overall match priority...
7163                        if (info.priority > maxMatchPrio) {
7164                            maxMatchPrio = info.priority;
7165                        }
7166                        // ...and the highest-priority default browser match
7167                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7168                            if (defaultBrowserMatch == null
7169                                    || (defaultBrowserMatch.priority < info.priority)) {
7170                                if (debug) {
7171                                    Slog.v(TAG, "Considering default browser match " + info);
7172                                }
7173                                defaultBrowserMatch = info;
7174                            }
7175                        }
7176                    }
7177                    if (defaultBrowserMatch != null
7178                            && defaultBrowserMatch.priority >= maxMatchPrio
7179                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7180                    {
7181                        if (debug) {
7182                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7183                        }
7184                        result.add(defaultBrowserMatch);
7185                    } else {
7186                        result.addAll(matchAllList);
7187                    }
7188                }
7189
7190                // If there is nothing selected, add all candidates and remove the ones that the user
7191                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7192                if (result.size() == 0) {
7193                    result.addAll(candidates);
7194                    result.removeAll(neverList);
7195                }
7196            }
7197        }
7198        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7199            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7200                    result.size());
7201            for (ResolveInfo info : result) {
7202                Slog.v(TAG, "  + " + info.activityInfo);
7203            }
7204        }
7205        return result;
7206    }
7207
7208    // Returns a packed value as a long:
7209    //
7210    // high 'int'-sized word: link status: undefined/ask/never/always.
7211    // low 'int'-sized word: relative priority among 'always' results.
7212    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7213        long result = ps.getDomainVerificationStatusForUser(userId);
7214        // if none available, get the master status
7215        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7216            if (ps.getIntentFilterVerificationInfo() != null) {
7217                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7218            }
7219        }
7220        return result;
7221    }
7222
7223    private ResolveInfo querySkipCurrentProfileIntents(
7224            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7225            int flags, int sourceUserId) {
7226        if (matchingFilters != null) {
7227            int size = matchingFilters.size();
7228            for (int i = 0; i < size; i ++) {
7229                CrossProfileIntentFilter filter = matchingFilters.get(i);
7230                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7231                    // Checking if there are activities in the target user that can handle the
7232                    // intent.
7233                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7234                            resolvedType, flags, sourceUserId);
7235                    if (resolveInfo != null) {
7236                        return resolveInfo;
7237                    }
7238                }
7239            }
7240        }
7241        return null;
7242    }
7243
7244    // Return matching ResolveInfo in target user if any.
7245    private ResolveInfo queryCrossProfileIntents(
7246            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7247            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7248        if (matchingFilters != null) {
7249            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7250            // match the same intent. For performance reasons, it is better not to
7251            // run queryIntent twice for the same userId
7252            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7253            int size = matchingFilters.size();
7254            for (int i = 0; i < size; i++) {
7255                CrossProfileIntentFilter filter = matchingFilters.get(i);
7256                int targetUserId = filter.getTargetUserId();
7257                boolean skipCurrentProfile =
7258                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7259                boolean skipCurrentProfileIfNoMatchFound =
7260                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7261                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7262                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7263                    // Checking if there are activities in the target user that can handle the
7264                    // intent.
7265                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7266                            resolvedType, flags, sourceUserId);
7267                    if (resolveInfo != null) return resolveInfo;
7268                    alreadyTriedUserIds.put(targetUserId, true);
7269                }
7270            }
7271        }
7272        return null;
7273    }
7274
7275    /**
7276     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7277     * will forward the intent to the filter's target user.
7278     * Otherwise, returns null.
7279     */
7280    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7281            String resolvedType, int flags, int sourceUserId) {
7282        int targetUserId = filter.getTargetUserId();
7283        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7284                resolvedType, flags, targetUserId);
7285        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7286            // If all the matches in the target profile are suspended, return null.
7287            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7288                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7289                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7290                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7291                            targetUserId);
7292                }
7293            }
7294        }
7295        return null;
7296    }
7297
7298    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7299            int sourceUserId, int targetUserId) {
7300        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7301        long ident = Binder.clearCallingIdentity();
7302        boolean targetIsProfile;
7303        try {
7304            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7305        } finally {
7306            Binder.restoreCallingIdentity(ident);
7307        }
7308        String className;
7309        if (targetIsProfile) {
7310            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7311        } else {
7312            className = FORWARD_INTENT_TO_PARENT;
7313        }
7314        ComponentName forwardingActivityComponentName = new ComponentName(
7315                mAndroidApplication.packageName, className);
7316        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7317                sourceUserId);
7318        if (!targetIsProfile) {
7319            forwardingActivityInfo.showUserIcon = targetUserId;
7320            forwardingResolveInfo.noResourceId = true;
7321        }
7322        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7323        forwardingResolveInfo.priority = 0;
7324        forwardingResolveInfo.preferredOrder = 0;
7325        forwardingResolveInfo.match = 0;
7326        forwardingResolveInfo.isDefault = true;
7327        forwardingResolveInfo.filter = filter;
7328        forwardingResolveInfo.targetUserId = targetUserId;
7329        return forwardingResolveInfo;
7330    }
7331
7332    @Override
7333    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7334            Intent[] specifics, String[] specificTypes, Intent intent,
7335            String resolvedType, int flags, int userId) {
7336        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7337                specificTypes, intent, resolvedType, flags, userId));
7338    }
7339
7340    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7341            Intent[] specifics, String[] specificTypes, Intent intent,
7342            String resolvedType, int flags, int userId) {
7343        if (!sUserManager.exists(userId)) return Collections.emptyList();
7344        final int callingUid = Binder.getCallingUid();
7345        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7346                false /*includeInstantApps*/);
7347        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7348                false /*requireFullPermission*/, false /*checkShell*/,
7349                "query intent activity options");
7350        final String resultsAction = intent.getAction();
7351
7352        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7353                | PackageManager.GET_RESOLVED_FILTER, userId);
7354
7355        if (DEBUG_INTENT_MATCHING) {
7356            Log.v(TAG, "Query " + intent + ": " + results);
7357        }
7358
7359        int specificsPos = 0;
7360        int N;
7361
7362        // todo: note that the algorithm used here is O(N^2).  This
7363        // isn't a problem in our current environment, but if we start running
7364        // into situations where we have more than 5 or 10 matches then this
7365        // should probably be changed to something smarter...
7366
7367        // First we go through and resolve each of the specific items
7368        // that were supplied, taking care of removing any corresponding
7369        // duplicate items in the generic resolve list.
7370        if (specifics != null) {
7371            for (int i=0; i<specifics.length; i++) {
7372                final Intent sintent = specifics[i];
7373                if (sintent == null) {
7374                    continue;
7375                }
7376
7377                if (DEBUG_INTENT_MATCHING) {
7378                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7379                }
7380
7381                String action = sintent.getAction();
7382                if (resultsAction != null && resultsAction.equals(action)) {
7383                    // If this action was explicitly requested, then don't
7384                    // remove things that have it.
7385                    action = null;
7386                }
7387
7388                ResolveInfo ri = null;
7389                ActivityInfo ai = null;
7390
7391                ComponentName comp = sintent.getComponent();
7392                if (comp == null) {
7393                    ri = resolveIntent(
7394                        sintent,
7395                        specificTypes != null ? specificTypes[i] : null,
7396                            flags, userId);
7397                    if (ri == null) {
7398                        continue;
7399                    }
7400                    if (ri == mResolveInfo) {
7401                        // ACK!  Must do something better with this.
7402                    }
7403                    ai = ri.activityInfo;
7404                    comp = new ComponentName(ai.applicationInfo.packageName,
7405                            ai.name);
7406                } else {
7407                    ai = getActivityInfo(comp, flags, userId);
7408                    if (ai == null) {
7409                        continue;
7410                    }
7411                }
7412
7413                // Look for any generic query activities that are duplicates
7414                // of this specific one, and remove them from the results.
7415                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7416                N = results.size();
7417                int j;
7418                for (j=specificsPos; j<N; j++) {
7419                    ResolveInfo sri = results.get(j);
7420                    if ((sri.activityInfo.name.equals(comp.getClassName())
7421                            && sri.activityInfo.applicationInfo.packageName.equals(
7422                                    comp.getPackageName()))
7423                        || (action != null && sri.filter.matchAction(action))) {
7424                        results.remove(j);
7425                        if (DEBUG_INTENT_MATCHING) Log.v(
7426                            TAG, "Removing duplicate item from " + j
7427                            + " due to specific " + specificsPos);
7428                        if (ri == null) {
7429                            ri = sri;
7430                        }
7431                        j--;
7432                        N--;
7433                    }
7434                }
7435
7436                // Add this specific item to its proper place.
7437                if (ri == null) {
7438                    ri = new ResolveInfo();
7439                    ri.activityInfo = ai;
7440                }
7441                results.add(specificsPos, ri);
7442                ri.specificIndex = i;
7443                specificsPos++;
7444            }
7445        }
7446
7447        // Now we go through the remaining generic results and remove any
7448        // duplicate actions that are found here.
7449        N = results.size();
7450        for (int i=specificsPos; i<N-1; i++) {
7451            final ResolveInfo rii = results.get(i);
7452            if (rii.filter == null) {
7453                continue;
7454            }
7455
7456            // Iterate over all of the actions of this result's intent
7457            // filter...  typically this should be just one.
7458            final Iterator<String> it = rii.filter.actionsIterator();
7459            if (it == null) {
7460                continue;
7461            }
7462            while (it.hasNext()) {
7463                final String action = it.next();
7464                if (resultsAction != null && resultsAction.equals(action)) {
7465                    // If this action was explicitly requested, then don't
7466                    // remove things that have it.
7467                    continue;
7468                }
7469                for (int j=i+1; j<N; j++) {
7470                    final ResolveInfo rij = results.get(j);
7471                    if (rij.filter != null && rij.filter.hasAction(action)) {
7472                        results.remove(j);
7473                        if (DEBUG_INTENT_MATCHING) Log.v(
7474                            TAG, "Removing duplicate item from " + j
7475                            + " due to action " + action + " at " + i);
7476                        j--;
7477                        N--;
7478                    }
7479                }
7480            }
7481
7482            // If the caller didn't request filter information, drop it now
7483            // so we don't have to marshall/unmarshall it.
7484            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7485                rii.filter = null;
7486            }
7487        }
7488
7489        // Filter out the caller activity if so requested.
7490        if (caller != null) {
7491            N = results.size();
7492            for (int i=0; i<N; i++) {
7493                ActivityInfo ainfo = results.get(i).activityInfo;
7494                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7495                        && caller.getClassName().equals(ainfo.name)) {
7496                    results.remove(i);
7497                    break;
7498                }
7499            }
7500        }
7501
7502        // If the caller didn't request filter information,
7503        // drop them now so we don't have to
7504        // marshall/unmarshall it.
7505        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7506            N = results.size();
7507            for (int i=0; i<N; i++) {
7508                results.get(i).filter = null;
7509            }
7510        }
7511
7512        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7513        return results;
7514    }
7515
7516    @Override
7517    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7518            String resolvedType, int flags, int userId) {
7519        return new ParceledListSlice<>(
7520                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7521                        false /*allowDynamicSplits*/));
7522    }
7523
7524    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7525            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7526        if (!sUserManager.exists(userId)) return Collections.emptyList();
7527        final int callingUid = Binder.getCallingUid();
7528        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7529                false /*requireFullPermission*/, false /*checkShell*/,
7530                "query intent receivers");
7531        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7532        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7533                false /*includeInstantApps*/);
7534        ComponentName comp = intent.getComponent();
7535        if (comp == null) {
7536            if (intent.getSelector() != null) {
7537                intent = intent.getSelector();
7538                comp = intent.getComponent();
7539            }
7540        }
7541        if (comp != null) {
7542            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7543            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7544            if (ai != null) {
7545                // When specifying an explicit component, we prevent the activity from being
7546                // used when either 1) the calling package is normal and the activity is within
7547                // an instant application or 2) the calling package is ephemeral and the
7548                // activity is not visible to instant applications.
7549                final boolean matchInstantApp =
7550                        (flags & PackageManager.MATCH_INSTANT) != 0;
7551                final boolean matchVisibleToInstantAppOnly =
7552                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7553                final boolean matchExplicitlyVisibleOnly =
7554                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7555                final boolean isCallerInstantApp =
7556                        instantAppPkgName != null;
7557                final boolean isTargetSameInstantApp =
7558                        comp.getPackageName().equals(instantAppPkgName);
7559                final boolean isTargetInstantApp =
7560                        (ai.applicationInfo.privateFlags
7561                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7562                final boolean isTargetVisibleToInstantApp =
7563                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7564                final boolean isTargetExplicitlyVisibleToInstantApp =
7565                        isTargetVisibleToInstantApp
7566                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7567                final boolean isTargetHiddenFromInstantApp =
7568                        !isTargetVisibleToInstantApp
7569                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7570                final boolean blockResolution =
7571                        !isTargetSameInstantApp
7572                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7573                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7574                                        && isTargetHiddenFromInstantApp));
7575                if (!blockResolution) {
7576                    ResolveInfo ri = new ResolveInfo();
7577                    ri.activityInfo = ai;
7578                    list.add(ri);
7579                }
7580            }
7581            return applyPostResolutionFilter(
7582                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7583        }
7584
7585        // reader
7586        synchronized (mPackages) {
7587            String pkgName = intent.getPackage();
7588            if (pkgName == null) {
7589                final List<ResolveInfo> result =
7590                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7591                return applyPostResolutionFilter(
7592                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7593            }
7594            final PackageParser.Package pkg = mPackages.get(pkgName);
7595            if (pkg != null) {
7596                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7597                        intent, resolvedType, flags, pkg.receivers, userId);
7598                return applyPostResolutionFilter(
7599                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7600            }
7601            return Collections.emptyList();
7602        }
7603    }
7604
7605    @Override
7606    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7607        final int callingUid = Binder.getCallingUid();
7608        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7609    }
7610
7611    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7612            int userId, int callingUid) {
7613        if (!sUserManager.exists(userId)) return null;
7614        flags = updateFlagsForResolve(
7615                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7616        List<ResolveInfo> query = queryIntentServicesInternal(
7617                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7618        if (query != null) {
7619            if (query.size() >= 1) {
7620                // If there is more than one service with the same priority,
7621                // just arbitrarily pick the first one.
7622                return query.get(0);
7623            }
7624        }
7625        return null;
7626    }
7627
7628    @Override
7629    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7630            String resolvedType, int flags, int userId) {
7631        final int callingUid = Binder.getCallingUid();
7632        return new ParceledListSlice<>(queryIntentServicesInternal(
7633                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7634    }
7635
7636    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7637            String resolvedType, int flags, int userId, int callingUid,
7638            boolean includeInstantApps) {
7639        if (!sUserManager.exists(userId)) return Collections.emptyList();
7640        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7641                false /*requireFullPermission*/, false /*checkShell*/,
7642                "query intent receivers");
7643        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7644        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7645        ComponentName comp = intent.getComponent();
7646        if (comp == null) {
7647            if (intent.getSelector() != null) {
7648                intent = intent.getSelector();
7649                comp = intent.getComponent();
7650            }
7651        }
7652        if (comp != null) {
7653            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7654            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7655            if (si != null) {
7656                // When specifying an explicit component, we prevent the service from being
7657                // used when either 1) the service is in an instant application and the
7658                // caller is not the same instant application or 2) the calling package is
7659                // ephemeral and the activity is not visible to ephemeral applications.
7660                final boolean matchInstantApp =
7661                        (flags & PackageManager.MATCH_INSTANT) != 0;
7662                final boolean matchVisibleToInstantAppOnly =
7663                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7664                final boolean isCallerInstantApp =
7665                        instantAppPkgName != null;
7666                final boolean isTargetSameInstantApp =
7667                        comp.getPackageName().equals(instantAppPkgName);
7668                final boolean isTargetInstantApp =
7669                        (si.applicationInfo.privateFlags
7670                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7671                final boolean isTargetHiddenFromInstantApp =
7672                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7673                final boolean blockResolution =
7674                        !isTargetSameInstantApp
7675                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7676                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7677                                        && isTargetHiddenFromInstantApp));
7678                if (!blockResolution) {
7679                    final ResolveInfo ri = new ResolveInfo();
7680                    ri.serviceInfo = si;
7681                    list.add(ri);
7682                }
7683            }
7684            return list;
7685        }
7686
7687        // reader
7688        synchronized (mPackages) {
7689            String pkgName = intent.getPackage();
7690            if (pkgName == null) {
7691                return applyPostServiceResolutionFilter(
7692                        mServices.queryIntent(intent, resolvedType, flags, userId),
7693                        instantAppPkgName);
7694            }
7695            final PackageParser.Package pkg = mPackages.get(pkgName);
7696            if (pkg != null) {
7697                return applyPostServiceResolutionFilter(
7698                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7699                                userId),
7700                        instantAppPkgName);
7701            }
7702            return Collections.emptyList();
7703        }
7704    }
7705
7706    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7707            String instantAppPkgName) {
7708        if (instantAppPkgName == null) {
7709            return resolveInfos;
7710        }
7711        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7712            final ResolveInfo info = resolveInfos.get(i);
7713            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7714            // allow services that are defined in the provided package
7715            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7716                if (info.serviceInfo.splitName != null
7717                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7718                                info.serviceInfo.splitName)) {
7719                    // requested service is defined in a split that hasn't been installed yet.
7720                    // add the installer to the resolve list
7721                    if (DEBUG_INSTANT) {
7722                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7723                    }
7724                    final ResolveInfo installerInfo = new ResolveInfo(
7725                            mInstantAppInstallerInfo);
7726                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7727                            null /* installFailureActivity */,
7728                            info.serviceInfo.packageName,
7729                            info.serviceInfo.applicationInfo.longVersionCode,
7730                            info.serviceInfo.splitName);
7731                    // add a non-generic filter
7732                    installerInfo.filter = new IntentFilter();
7733                    // load resources from the correct package
7734                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7735                    resolveInfos.set(i, installerInfo);
7736                }
7737                continue;
7738            }
7739            // allow services that have been explicitly exposed to ephemeral apps
7740            if (!isEphemeralApp
7741                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7742                continue;
7743            }
7744            resolveInfos.remove(i);
7745        }
7746        return resolveInfos;
7747    }
7748
7749    @Override
7750    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7751            String resolvedType, int flags, int userId) {
7752        return new ParceledListSlice<>(
7753                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7754    }
7755
7756    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7757            Intent intent, String resolvedType, int flags, int userId) {
7758        if (!sUserManager.exists(userId)) return Collections.emptyList();
7759        final int callingUid = Binder.getCallingUid();
7760        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7761        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7762                false /*includeInstantApps*/);
7763        ComponentName comp = intent.getComponent();
7764        if (comp == null) {
7765            if (intent.getSelector() != null) {
7766                intent = intent.getSelector();
7767                comp = intent.getComponent();
7768            }
7769        }
7770        if (comp != null) {
7771            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7772            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7773            if (pi != null) {
7774                // When specifying an explicit component, we prevent the provider from being
7775                // used when either 1) the provider is in an instant application and the
7776                // caller is not the same instant application or 2) the calling package is an
7777                // instant application and the provider is not visible to instant applications.
7778                final boolean matchInstantApp =
7779                        (flags & PackageManager.MATCH_INSTANT) != 0;
7780                final boolean matchVisibleToInstantAppOnly =
7781                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7782                final boolean isCallerInstantApp =
7783                        instantAppPkgName != null;
7784                final boolean isTargetSameInstantApp =
7785                        comp.getPackageName().equals(instantAppPkgName);
7786                final boolean isTargetInstantApp =
7787                        (pi.applicationInfo.privateFlags
7788                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7789                final boolean isTargetHiddenFromInstantApp =
7790                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7791                final boolean blockResolution =
7792                        !isTargetSameInstantApp
7793                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7794                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7795                                        && isTargetHiddenFromInstantApp));
7796                if (!blockResolution) {
7797                    final ResolveInfo ri = new ResolveInfo();
7798                    ri.providerInfo = pi;
7799                    list.add(ri);
7800                }
7801            }
7802            return list;
7803        }
7804
7805        // reader
7806        synchronized (mPackages) {
7807            String pkgName = intent.getPackage();
7808            if (pkgName == null) {
7809                return applyPostContentProviderResolutionFilter(
7810                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7811                        instantAppPkgName);
7812            }
7813            final PackageParser.Package pkg = mPackages.get(pkgName);
7814            if (pkg != null) {
7815                return applyPostContentProviderResolutionFilter(
7816                        mProviders.queryIntentForPackage(
7817                        intent, resolvedType, flags, pkg.providers, userId),
7818                        instantAppPkgName);
7819            }
7820            return Collections.emptyList();
7821        }
7822    }
7823
7824    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7825            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7826        if (instantAppPkgName == null) {
7827            return resolveInfos;
7828        }
7829        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7830            final ResolveInfo info = resolveInfos.get(i);
7831            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7832            // allow providers that are defined in the provided package
7833            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7834                if (info.providerInfo.splitName != null
7835                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7836                                info.providerInfo.splitName)) {
7837                    // requested provider is defined in a split that hasn't been installed yet.
7838                    // add the installer to the resolve list
7839                    if (DEBUG_INSTANT) {
7840                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7841                    }
7842                    final ResolveInfo installerInfo = new ResolveInfo(
7843                            mInstantAppInstallerInfo);
7844                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7845                            null /*failureActivity*/,
7846                            info.providerInfo.packageName,
7847                            info.providerInfo.applicationInfo.longVersionCode,
7848                            info.providerInfo.splitName);
7849                    // add a non-generic filter
7850                    installerInfo.filter = new IntentFilter();
7851                    // load resources from the correct package
7852                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7853                    resolveInfos.set(i, installerInfo);
7854                }
7855                continue;
7856            }
7857            // allow providers that have been explicitly exposed to instant applications
7858            if (!isEphemeralApp
7859                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7860                continue;
7861            }
7862            resolveInfos.remove(i);
7863        }
7864        return resolveInfos;
7865    }
7866
7867    @Override
7868    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7869        final int callingUid = Binder.getCallingUid();
7870        if (getInstantAppPackageName(callingUid) != null) {
7871            return ParceledListSlice.emptyList();
7872        }
7873        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7874        flags = updateFlagsForPackage(flags, userId, null);
7875        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7876        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7877                false /* requireFullPermission */, false /* checkShell */,
7878                "get installed packages");
7879
7880        // writer
7881        synchronized (mPackages) {
7882            ArrayList<PackageInfo> list;
7883            if (listUninstalled) {
7884                list = new ArrayList<>(mSettings.mPackages.size());
7885                for (PackageSetting ps : mSettings.mPackages.values()) {
7886                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7887                        continue;
7888                    }
7889                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7890                        continue;
7891                    }
7892                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7893                    if (pi != null) {
7894                        list.add(pi);
7895                    }
7896                }
7897            } else {
7898                list = new ArrayList<>(mPackages.size());
7899                for (PackageParser.Package p : mPackages.values()) {
7900                    final PackageSetting ps = (PackageSetting) p.mExtras;
7901                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7902                        continue;
7903                    }
7904                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7905                        continue;
7906                    }
7907                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7908                            p.mExtras, flags, userId);
7909                    if (pi != null) {
7910                        list.add(pi);
7911                    }
7912                }
7913            }
7914
7915            return new ParceledListSlice<>(list);
7916        }
7917    }
7918
7919    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7920            String[] permissions, boolean[] tmp, int flags, int userId) {
7921        int numMatch = 0;
7922        final PermissionsState permissionsState = ps.getPermissionsState();
7923        for (int i=0; i<permissions.length; i++) {
7924            final String permission = permissions[i];
7925            if (permissionsState.hasPermission(permission, userId)) {
7926                tmp[i] = true;
7927                numMatch++;
7928            } else {
7929                tmp[i] = false;
7930            }
7931        }
7932        if (numMatch == 0) {
7933            return;
7934        }
7935        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7936
7937        // The above might return null in cases of uninstalled apps or install-state
7938        // skew across users/profiles.
7939        if (pi != null) {
7940            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7941                if (numMatch == permissions.length) {
7942                    pi.requestedPermissions = permissions;
7943                } else {
7944                    pi.requestedPermissions = new String[numMatch];
7945                    numMatch = 0;
7946                    for (int i=0; i<permissions.length; i++) {
7947                        if (tmp[i]) {
7948                            pi.requestedPermissions[numMatch] = permissions[i];
7949                            numMatch++;
7950                        }
7951                    }
7952                }
7953            }
7954            list.add(pi);
7955        }
7956    }
7957
7958    @Override
7959    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7960            String[] permissions, int flags, int userId) {
7961        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7962        flags = updateFlagsForPackage(flags, userId, permissions);
7963        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7964                true /* requireFullPermission */, false /* checkShell */,
7965                "get packages holding permissions");
7966        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7967
7968        // writer
7969        synchronized (mPackages) {
7970            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7971            boolean[] tmpBools = new boolean[permissions.length];
7972            if (listUninstalled) {
7973                for (PackageSetting ps : mSettings.mPackages.values()) {
7974                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7975                            userId);
7976                }
7977            } else {
7978                for (PackageParser.Package pkg : mPackages.values()) {
7979                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7980                    if (ps != null) {
7981                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7982                                userId);
7983                    }
7984                }
7985            }
7986
7987            return new ParceledListSlice<PackageInfo>(list);
7988        }
7989    }
7990
7991    @Override
7992    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7993        final int callingUid = Binder.getCallingUid();
7994        if (getInstantAppPackageName(callingUid) != null) {
7995            return ParceledListSlice.emptyList();
7996        }
7997        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7998        flags = updateFlagsForApplication(flags, userId, null);
7999        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8000
8001        mPermissionManager.enforceCrossUserPermission(
8002            callingUid,
8003            userId,
8004            false /* requireFullPermission */,
8005            false /* checkShell */,
8006            "get installed application info");
8007
8008        // writer
8009        synchronized (mPackages) {
8010            ArrayList<ApplicationInfo> list;
8011            if (listUninstalled) {
8012                list = new ArrayList<>(mSettings.mPackages.size());
8013                for (PackageSetting ps : mSettings.mPackages.values()) {
8014                    ApplicationInfo ai;
8015                    int effectiveFlags = flags;
8016                    if (ps.isSystem()) {
8017                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8018                    }
8019                    if (ps.pkg != null) {
8020                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8021                            continue;
8022                        }
8023                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8024                            continue;
8025                        }
8026                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8027                                ps.readUserState(userId), userId);
8028                        if (ai != null) {
8029                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8030                        }
8031                    } else {
8032                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8033                        // and already converts to externally visible package name
8034                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8035                                callingUid, effectiveFlags, userId);
8036                    }
8037                    if (ai != null) {
8038                        list.add(ai);
8039                    }
8040                }
8041            } else {
8042                list = new ArrayList<>(mPackages.size());
8043                for (PackageParser.Package p : mPackages.values()) {
8044                    if (p.mExtras != null) {
8045                        PackageSetting ps = (PackageSetting) p.mExtras;
8046                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8047                            continue;
8048                        }
8049                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8050                            continue;
8051                        }
8052                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8053                                ps.readUserState(userId), userId);
8054                        if (ai != null) {
8055                            ai.packageName = resolveExternalPackageNameLPr(p);
8056                            list.add(ai);
8057                        }
8058                    }
8059                }
8060            }
8061
8062            return new ParceledListSlice<>(list);
8063        }
8064    }
8065
8066    @Override
8067    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8068        if (HIDE_EPHEMERAL_APIS) {
8069            return null;
8070        }
8071        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8072            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8073                    "getEphemeralApplications");
8074        }
8075        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8076                true /* requireFullPermission */, false /* checkShell */,
8077                "getEphemeralApplications");
8078        synchronized (mPackages) {
8079            List<InstantAppInfo> instantApps = mInstantAppRegistry
8080                    .getInstantAppsLPr(userId);
8081            if (instantApps != null) {
8082                return new ParceledListSlice<>(instantApps);
8083            }
8084        }
8085        return null;
8086    }
8087
8088    @Override
8089    public boolean isInstantApp(String packageName, int userId) {
8090        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8091                true /* requireFullPermission */, false /* checkShell */,
8092                "isInstantApp");
8093        if (HIDE_EPHEMERAL_APIS) {
8094            return false;
8095        }
8096
8097        synchronized (mPackages) {
8098            int callingUid = Binder.getCallingUid();
8099            if (Process.isIsolated(callingUid)) {
8100                callingUid = mIsolatedOwners.get(callingUid);
8101            }
8102            final PackageSetting ps = mSettings.mPackages.get(packageName);
8103            PackageParser.Package pkg = mPackages.get(packageName);
8104            final boolean returnAllowed =
8105                    ps != null
8106                    && (isCallerSameApp(packageName, callingUid)
8107                            || canViewInstantApps(callingUid, userId)
8108                            || mInstantAppRegistry.isInstantAccessGranted(
8109                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8110            if (returnAllowed) {
8111                return ps.getInstantApp(userId);
8112            }
8113        }
8114        return false;
8115    }
8116
8117    @Override
8118    public byte[] getInstantAppCookie(String packageName, int userId) {
8119        if (HIDE_EPHEMERAL_APIS) {
8120            return null;
8121        }
8122
8123        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8124                true /* requireFullPermission */, false /* checkShell */,
8125                "getInstantAppCookie");
8126        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8127            return null;
8128        }
8129        synchronized (mPackages) {
8130            return mInstantAppRegistry.getInstantAppCookieLPw(
8131                    packageName, userId);
8132        }
8133    }
8134
8135    @Override
8136    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8137        if (HIDE_EPHEMERAL_APIS) {
8138            return true;
8139        }
8140
8141        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8142                true /* requireFullPermission */, true /* checkShell */,
8143                "setInstantAppCookie");
8144        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8145            return false;
8146        }
8147        synchronized (mPackages) {
8148            return mInstantAppRegistry.setInstantAppCookieLPw(
8149                    packageName, cookie, userId);
8150        }
8151    }
8152
8153    @Override
8154    public Bitmap getInstantAppIcon(String packageName, int userId) {
8155        if (HIDE_EPHEMERAL_APIS) {
8156            return null;
8157        }
8158
8159        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8160            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8161                    "getInstantAppIcon");
8162        }
8163        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8164                true /* requireFullPermission */, false /* checkShell */,
8165                "getInstantAppIcon");
8166
8167        synchronized (mPackages) {
8168            return mInstantAppRegistry.getInstantAppIconLPw(
8169                    packageName, userId);
8170        }
8171    }
8172
8173    private boolean isCallerSameApp(String packageName, int uid) {
8174        PackageParser.Package pkg = mPackages.get(packageName);
8175        return pkg != null
8176                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8177    }
8178
8179    @Override
8180    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8181        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8182            return ParceledListSlice.emptyList();
8183        }
8184        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8185    }
8186
8187    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8188        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8189
8190        // reader
8191        synchronized (mPackages) {
8192            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8193            final int userId = UserHandle.getCallingUserId();
8194            while (i.hasNext()) {
8195                final PackageParser.Package p = i.next();
8196                if (p.applicationInfo == null) continue;
8197
8198                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8199                        && !p.applicationInfo.isDirectBootAware();
8200                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8201                        && p.applicationInfo.isDirectBootAware();
8202
8203                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8204                        && (!mSafeMode || isSystemApp(p))
8205                        && (matchesUnaware || matchesAware)) {
8206                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8207                    if (ps != null) {
8208                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8209                                ps.readUserState(userId), userId);
8210                        if (ai != null) {
8211                            finalList.add(ai);
8212                        }
8213                    }
8214                }
8215            }
8216        }
8217
8218        return finalList;
8219    }
8220
8221    @Override
8222    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8223        return resolveContentProviderInternal(name, flags, userId);
8224    }
8225
8226    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8227        if (!sUserManager.exists(userId)) return null;
8228        flags = updateFlagsForComponent(flags, userId, name);
8229        final int callingUid = Binder.getCallingUid();
8230        synchronized (mPackages) {
8231            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8232            PackageSetting ps = provider != null
8233                    ? mSettings.mPackages.get(provider.owner.packageName)
8234                    : null;
8235            if (ps != null) {
8236                // provider not enabled
8237                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8238                    return null;
8239                }
8240                final ComponentName component =
8241                        new ComponentName(provider.info.packageName, provider.info.name);
8242                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8243                    return null;
8244                }
8245                return PackageParser.generateProviderInfo(
8246                        provider, flags, ps.readUserState(userId), userId);
8247            }
8248            return null;
8249        }
8250    }
8251
8252    /**
8253     * @deprecated
8254     */
8255    @Deprecated
8256    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8257        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8258            return;
8259        }
8260        // reader
8261        synchronized (mPackages) {
8262            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8263                    .entrySet().iterator();
8264            final int userId = UserHandle.getCallingUserId();
8265            while (i.hasNext()) {
8266                Map.Entry<String, PackageParser.Provider> entry = i.next();
8267                PackageParser.Provider p = entry.getValue();
8268                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8269
8270                if (ps != null && p.syncable
8271                        && (!mSafeMode || (p.info.applicationInfo.flags
8272                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8273                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8274                            ps.readUserState(userId), userId);
8275                    if (info != null) {
8276                        outNames.add(entry.getKey());
8277                        outInfo.add(info);
8278                    }
8279                }
8280            }
8281        }
8282    }
8283
8284    @Override
8285    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8286            int uid, int flags, String metaDataKey) {
8287        final int callingUid = Binder.getCallingUid();
8288        final int userId = processName != null ? UserHandle.getUserId(uid)
8289                : UserHandle.getCallingUserId();
8290        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8291        flags = updateFlagsForComponent(flags, userId, processName);
8292        ArrayList<ProviderInfo> finalList = null;
8293        // reader
8294        synchronized (mPackages) {
8295            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8296            while (i.hasNext()) {
8297                final PackageParser.Provider p = i.next();
8298                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8299                if (ps != null && p.info.authority != null
8300                        && (processName == null
8301                                || (p.info.processName.equals(processName)
8302                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8303                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8304
8305                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8306                    // parameter.
8307                    if (metaDataKey != null
8308                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8309                        continue;
8310                    }
8311                    final ComponentName component =
8312                            new ComponentName(p.info.packageName, p.info.name);
8313                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8314                        continue;
8315                    }
8316                    if (finalList == null) {
8317                        finalList = new ArrayList<ProviderInfo>(3);
8318                    }
8319                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8320                            ps.readUserState(userId), userId);
8321                    if (info != null) {
8322                        finalList.add(info);
8323                    }
8324                }
8325            }
8326        }
8327
8328        if (finalList != null) {
8329            Collections.sort(finalList, mProviderInitOrderSorter);
8330            return new ParceledListSlice<ProviderInfo>(finalList);
8331        }
8332
8333        return ParceledListSlice.emptyList();
8334    }
8335
8336    @Override
8337    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8338        // reader
8339        synchronized (mPackages) {
8340            final int callingUid = Binder.getCallingUid();
8341            final int callingUserId = UserHandle.getUserId(callingUid);
8342            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8343            if (ps == null) return null;
8344            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8345                return null;
8346            }
8347            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8348            return PackageParser.generateInstrumentationInfo(i, flags);
8349        }
8350    }
8351
8352    @Override
8353    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8354            String targetPackage, int flags) {
8355        final int callingUid = Binder.getCallingUid();
8356        final int callingUserId = UserHandle.getUserId(callingUid);
8357        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8358        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8359            return ParceledListSlice.emptyList();
8360        }
8361        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8362    }
8363
8364    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8365            int flags) {
8366        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8367
8368        // reader
8369        synchronized (mPackages) {
8370            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8371            while (i.hasNext()) {
8372                final PackageParser.Instrumentation p = i.next();
8373                if (targetPackage == null
8374                        || targetPackage.equals(p.info.targetPackage)) {
8375                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8376                            flags);
8377                    if (ii != null) {
8378                        finalList.add(ii);
8379                    }
8380                }
8381            }
8382        }
8383
8384        return finalList;
8385    }
8386
8387    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8388        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8389        try {
8390            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8391        } finally {
8392            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8393        }
8394    }
8395
8396    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8397        final File[] files = scanDir.listFiles();
8398        if (ArrayUtils.isEmpty(files)) {
8399            Log.d(TAG, "No files in app dir " + scanDir);
8400            return;
8401        }
8402
8403        if (DEBUG_PACKAGE_SCANNING) {
8404            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8405                    + " flags=0x" + Integer.toHexString(parseFlags));
8406        }
8407        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8408                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8409                mParallelPackageParserCallback)) {
8410            // Submit files for parsing in parallel
8411            int fileCount = 0;
8412            for (File file : files) {
8413                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8414                        && !PackageInstallerService.isStageName(file.getName());
8415                if (!isPackage) {
8416                    // Ignore entries which are not packages
8417                    continue;
8418                }
8419                parallelPackageParser.submit(file, parseFlags);
8420                fileCount++;
8421            }
8422
8423            // Process results one by one
8424            for (; fileCount > 0; fileCount--) {
8425                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8426                Throwable throwable = parseResult.throwable;
8427                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8428
8429                if (throwable == null) {
8430                    // TODO(toddke): move lower in the scan chain
8431                    // Static shared libraries have synthetic package names
8432                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8433                        renameStaticSharedLibraryPackage(parseResult.pkg);
8434                    }
8435                    try {
8436                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8437                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8438                                    currentTime, null);
8439                        }
8440                    } catch (PackageManagerException e) {
8441                        errorCode = e.error;
8442                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8443                    }
8444                } else if (throwable instanceof PackageParser.PackageParserException) {
8445                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8446                            throwable;
8447                    errorCode = e.error;
8448                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8449                } else {
8450                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8451                            + parseResult.scanFile, throwable);
8452                }
8453
8454                // Delete invalid userdata apps
8455                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8456                        errorCode != PackageManager.INSTALL_SUCCEEDED) {
8457                    logCriticalInfo(Log.WARN,
8458                            "Deleting invalid package at " + parseResult.scanFile);
8459                    removeCodePathLI(parseResult.scanFile);
8460                }
8461            }
8462        }
8463    }
8464
8465    public static void reportSettingsProblem(int priority, String msg) {
8466        logCriticalInfo(priority, msg);
8467    }
8468
8469    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8470            boolean forceCollect, boolean skipVerify) throws PackageManagerException {
8471        // When upgrading from pre-N MR1, verify the package time stamp using the package
8472        // directory and not the APK file.
8473        final long lastModifiedTime = mIsPreNMR1Upgrade
8474                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8475        if (ps != null && !forceCollect
8476                && ps.codePathString.equals(pkg.codePath)
8477                && ps.timeStamp == lastModifiedTime
8478                && !isCompatSignatureUpdateNeeded(pkg)
8479                && !isRecoverSignatureUpdateNeeded(pkg)) {
8480            if (ps.signatures.mSigningDetails.signatures != null
8481                    && ps.signatures.mSigningDetails.signatures.length != 0
8482                    && ps.signatures.mSigningDetails.signatureSchemeVersion
8483                            != SignatureSchemeVersion.UNKNOWN) {
8484                // Optimization: reuse the existing cached signing data
8485                // if the package appears to be unchanged.
8486                pkg.mSigningDetails =
8487                        new PackageParser.SigningDetails(ps.signatures.mSigningDetails);
8488                return;
8489            }
8490
8491            Slog.w(TAG, "PackageSetting for " + ps.name
8492                    + " is missing signatures.  Collecting certs again to recover them.");
8493        } else {
8494            Slog.i(TAG, pkg.codePath + " changed; collecting certs" +
8495                    (forceCollect ? " (forced)" : ""));
8496        }
8497
8498        try {
8499            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8500            PackageParser.collectCertificates(pkg, skipVerify);
8501        } catch (PackageParserException e) {
8502            throw PackageManagerException.from(e);
8503        } finally {
8504            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8505        }
8506    }
8507
8508    /**
8509     * Clear the package profile if this was an upgrade and the package
8510     * version was updated.
8511     */
8512    private void maybeClearProfilesForUpgradesLI(
8513            @Nullable PackageSetting originalPkgSetting,
8514            @NonNull PackageParser.Package currentPkg) {
8515        if (originalPkgSetting == null || !isUpgrade()) {
8516          return;
8517        }
8518        if (originalPkgSetting.versionCode == currentPkg.mVersionCode) {
8519          return;
8520        }
8521
8522        clearAppProfilesLIF(currentPkg, UserHandle.USER_ALL);
8523        if (DEBUG_INSTALL) {
8524            Slog.d(TAG, originalPkgSetting.name
8525                  + " clear profile due to version change "
8526                  + originalPkgSetting.versionCode + " != "
8527                  + currentPkg.mVersionCode);
8528        }
8529    }
8530
8531    /**
8532     *  Traces a package scan.
8533     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8534     */
8535    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8536            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8537        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8538        try {
8539            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8540        } finally {
8541            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8542        }
8543    }
8544
8545    /**
8546     *  Scans a package and returns the newly parsed package.
8547     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8548     */
8549    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8550            long currentTime, UserHandle user) throws PackageManagerException {
8551        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8552        PackageParser pp = new PackageParser();
8553        pp.setSeparateProcesses(mSeparateProcesses);
8554        pp.setOnlyCoreApps(mOnlyCore);
8555        pp.setDisplayMetrics(mMetrics);
8556        pp.setCallback(mPackageParserCallback);
8557
8558        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8559        final PackageParser.Package pkg;
8560        try {
8561            pkg = pp.parsePackage(scanFile, parseFlags);
8562        } catch (PackageParserException e) {
8563            throw PackageManagerException.from(e);
8564        } finally {
8565            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8566        }
8567
8568        // Static shared libraries have synthetic package names
8569        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8570            renameStaticSharedLibraryPackage(pkg);
8571        }
8572
8573        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8574    }
8575
8576    /**
8577     *  Scans a package and returns the newly parsed package.
8578     *  @throws PackageManagerException on a parse error.
8579     */
8580    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8581            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8582            @Nullable UserHandle user)
8583                    throws PackageManagerException {
8584        // If the package has children and this is the first dive in the function
8585        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8586        // packages (parent and children) would be successfully scanned before the
8587        // actual scan since scanning mutates internal state and we want to atomically
8588        // install the package and its children.
8589        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8590            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8591                scanFlags |= SCAN_CHECK_ONLY;
8592            }
8593        } else {
8594            scanFlags &= ~SCAN_CHECK_ONLY;
8595        }
8596
8597        // Scan the parent
8598        PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags,
8599                scanFlags, currentTime, user);
8600
8601        // Scan the children
8602        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8603        for (int i = 0; i < childCount; i++) {
8604            PackageParser.Package childPackage = pkg.childPackages.get(i);
8605            addForInitLI(childPackage, parseFlags, scanFlags,
8606                    currentTime, user);
8607        }
8608
8609
8610        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8611            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8612        }
8613
8614        return scannedPkg;
8615    }
8616
8617    /**
8618     * Returns if full apk verification can be skipped for the whole package, including the splits.
8619     */
8620    private boolean canSkipFullPackageVerification(PackageParser.Package pkg) {
8621        if (!canSkipFullApkVerification(pkg.baseCodePath)) {
8622            return false;
8623        }
8624        // TODO: Allow base and splits to be verified individually.
8625        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8626            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8627                if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) {
8628                    return false;
8629                }
8630            }
8631        }
8632        return true;
8633    }
8634
8635    /**
8636     * Returns if full apk verification can be skipped, depending on current FSVerity setup and
8637     * whether the apk contains signed root hash.  Note that the signer's certificate still needs to
8638     * match one in a trusted source, and should be done separately.
8639     */
8640    private boolean canSkipFullApkVerification(String apkPath) {
8641        byte[] rootHashObserved = null;
8642        try {
8643            rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath);
8644            if (rootHashObserved == null) {
8645                return false;  // APK does not contain Merkle tree root hash.
8646            }
8647            synchronized (mInstallLock) {
8648                // Returns whether the observed root hash matches what kernel has.
8649                mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved);
8650                return true;
8651            }
8652        } catch (InstallerException | IOException | DigestException |
8653                NoSuchAlgorithmException e) {
8654            Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e);
8655        }
8656        return false;
8657    }
8658
8659    /**
8660     * Adds a new package to the internal data structures during platform initialization.
8661     * <p>After adding, the package is known to the system and available for querying.
8662     * <p>For packages located on the device ROM [eg. packages located in /system, /vendor,
8663     * etc...], additional checks are performed. Basic verification [such as ensuring
8664     * matching signatures, checking version codes, etc...] occurs if the package is
8665     * identical to a previously known package. If the package fails a signature check,
8666     * the version installed on /data will be removed. If the version of the new package
8667     * is less than or equal than the version on /data, it will be ignored.
8668     * <p>Regardless of the package location, the results are applied to the internal
8669     * structures and the package is made available to the rest of the system.
8670     * <p>NOTE: The return value should be removed. It's the passed in package object.
8671     */
8672    private PackageParser.Package addForInitLI(PackageParser.Package pkg,
8673            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8674            @Nullable UserHandle user)
8675                    throws PackageManagerException {
8676        final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0;
8677        final String renamedPkgName;
8678        final PackageSetting disabledPkgSetting;
8679        final boolean isSystemPkgUpdated;
8680        final boolean pkgAlreadyExists;
8681        PackageSetting pkgSetting;
8682
8683        // NOTE: installPackageLI() has the same code to setup the package's
8684        // application info. This probably should be done lower in the call
8685        // stack [such as scanPackageOnly()]. However, we verify the application
8686        // info prior to that [in scanPackageNew()] and thus have to setup
8687        // the application info early.
8688        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8689        pkg.setApplicationInfoCodePath(pkg.codePath);
8690        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8691        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8692        pkg.setApplicationInfoResourcePath(pkg.codePath);
8693        pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
8694        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8695
8696        synchronized (mPackages) {
8697            renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8698            final String realPkgName = getRealPackageName(pkg, renamedPkgName);
8699            if (realPkgName != null) {
8700                ensurePackageRenamed(pkg, renamedPkgName);
8701            }
8702            final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
8703            final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName);
8704            pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting;
8705            pkgAlreadyExists = pkgSetting != null;
8706            final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName;
8707            disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName);
8708            isSystemPkgUpdated = disabledPkgSetting != null;
8709
8710            if (DEBUG_INSTALL && isSystemPkgUpdated) {
8711                Slog.d(TAG, "updatedPkg = " + disabledPkgSetting);
8712            }
8713
8714            final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null)
8715                    ? mSettings.getSharedUserLPw(pkg.mSharedUserId,
8716                            0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true)
8717                    : null;
8718            if (DEBUG_PACKAGE_SCANNING
8719                    && (parseFlags & PackageParser.PARSE_CHATTY) != 0
8720                    && sharedUserSetting != null) {
8721                Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
8722                        + " (uid=" + sharedUserSetting.userId + "):"
8723                        + " packages=" + sharedUserSetting.packages);
8724            }
8725
8726            if (scanSystemPartition) {
8727                // Potentially prune child packages. If the application on the /system
8728                // partition has been updated via OTA, but, is still disabled by a
8729                // version on /data, cycle through all of its children packages and
8730                // remove children that are no longer defined.
8731                if (isSystemPkgUpdated) {
8732                    final int scannedChildCount = (pkg.childPackages != null)
8733                            ? pkg.childPackages.size() : 0;
8734                    final int disabledChildCount = disabledPkgSetting.childPackageNames != null
8735                            ? disabledPkgSetting.childPackageNames.size() : 0;
8736                    for (int i = 0; i < disabledChildCount; i++) {
8737                        String disabledChildPackageName =
8738                                disabledPkgSetting.childPackageNames.get(i);
8739                        boolean disabledPackageAvailable = false;
8740                        for (int j = 0; j < scannedChildCount; j++) {
8741                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8742                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8743                                disabledPackageAvailable = true;
8744                                break;
8745                            }
8746                        }
8747                        if (!disabledPackageAvailable) {
8748                            mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8749                        }
8750                    }
8751                    // we're updating the disabled package, so, scan it as the package setting
8752                    final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, null,
8753                            disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */,
8754                            null /* originalPkgSetting */, null, parseFlags, scanFlags,
8755                            (pkg == mPlatformPackage), user);
8756                    applyPolicy(pkg, parseFlags, scanFlags, mPlatformPackage);
8757                    scanPackageOnlyLI(request, mFactoryTest, -1L);
8758                }
8759            }
8760        }
8761
8762        final boolean newPkgChangedPaths =
8763                pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath);
8764        final boolean newPkgVersionGreater =
8765                pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode;
8766        final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated
8767                && newPkgChangedPaths && newPkgVersionGreater;
8768        if (isSystemPkgBetter) {
8769            // The version of the application on /system is greater than the version on
8770            // /data. Switch back to the application on /system.
8771            // It's safe to assume the application on /system will correctly scan. If not,
8772            // there won't be a working copy of the application.
8773            synchronized (mPackages) {
8774                // just remove the loaded entries from package lists
8775                mPackages.remove(pkgSetting.name);
8776            }
8777
8778            logCriticalInfo(Log.WARN,
8779                    "System package updated;"
8780                    + " name: " + pkgSetting.name
8781                    + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8782                    + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8783
8784            final InstallArgs args = createInstallArgsForExisting(
8785                    packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8786                    pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8787            args.cleanUpResourcesLI();
8788            synchronized (mPackages) {
8789                mSettings.enableSystemPackageLPw(pkgSetting.name);
8790            }
8791        }
8792
8793        if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) {
8794            // The version of the application on the /system partition is less than or
8795            // equal to the version on the /data partition. Even though the disabled system package
8796            // is likely to be replaced by a version on the /data partition, we make assumptions
8797            // that it's part of the mPackages collection during package manager initialization. So,
8798            // add it to mPackages if there isn't already a package in the collection and then throw
8799            // an exception to use the application already installed on the /data partition.
8800            synchronized (mPackages) {
8801                if (!mPackages.containsKey(pkg.packageName)) {
8802                    mPackages.put(pkg.packageName, pkg);
8803                }
8804            }
8805            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8806                    + pkg.codePath + " ignored: updated version " + pkgSetting.versionCode
8807                    + " better than this " + pkg.getLongVersionCode());
8808        }
8809
8810        // Verify certificates against what was last scanned. If it is an updated priv app, we will
8811        // force re-collecting certificate.
8812        final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced(
8813                disabledPkgSetting);
8814        // Full APK verification can be skipped during certificate collection, only if the file is
8815        // in verified partition, or can be verified on access (when apk verity is enabled). In both
8816        // cases, only data in Signing Block is verified instead of the whole file.
8817        final boolean skipVerify = ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) ||
8818                (forceCollect && canSkipFullPackageVerification(pkg));
8819        collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify);
8820
8821        // Reset profile if the application version is changed
8822        maybeClearProfilesForUpgradesLI(pkgSetting, pkg);
8823
8824        /*
8825         * A new system app appeared, but we already had a non-system one of the
8826         * same name installed earlier.
8827         */
8828        boolean shouldHideSystemApp = false;
8829        // A new application appeared on /system, but, we already have a copy of
8830        // the application installed on /data.
8831        if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists
8832                && !pkgSetting.isSystem()) {
8833
8834            if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails,
8835                    PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)
8836                            && !pkgSetting.signatures.mSigningDetails.checkCapability(
8837                                    pkg.mSigningDetails,
8838                                    PackageParser.SigningDetails.CertCapabilities.ROLLBACK)) {
8839                logCriticalInfo(Log.WARN,
8840                        "System package signature mismatch;"
8841                        + " name: " + pkgSetting.name);
8842                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8843                        "scanPackageInternalLI")) {
8844                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8845                }
8846                pkgSetting = null;
8847            } else if (newPkgVersionGreater) {
8848                // The application on /system is newer than the application on /data.
8849                // Simply remove the application on /data [keeping application data]
8850                // and replace it with the version on /system.
8851                logCriticalInfo(Log.WARN,
8852                        "System package enabled;"
8853                        + " name: " + pkgSetting.name
8854                        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8855                        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8856                InstallArgs args = createInstallArgsForExisting(
8857                        packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8858                        pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8859                synchronized (mInstallLock) {
8860                    args.cleanUpResourcesLI();
8861                }
8862            } else {
8863                // The application on /system is older than the application on /data. Hide
8864                // the application on /system and the version on /data will be scanned later
8865                // and re-added like an update.
8866                shouldHideSystemApp = true;
8867                logCriticalInfo(Log.INFO,
8868                        "System package disabled;"
8869                        + " name: " + pkgSetting.name
8870                        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8871                        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8872            }
8873        }
8874
8875        final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8876                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8877
8878        if (shouldHideSystemApp) {
8879            synchronized (mPackages) {
8880                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8881            }
8882        }
8883        return scannedPkg;
8884    }
8885
8886    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8887        // Derive the new package synthetic package name
8888        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8889                + pkg.staticSharedLibVersion);
8890    }
8891
8892    private static String fixProcessName(String defProcessName,
8893            String processName) {
8894        if (processName == null) {
8895            return defProcessName;
8896        }
8897        return processName;
8898    }
8899
8900    /**
8901     * Enforces that only the system UID or root's UID can call a method exposed
8902     * via Binder.
8903     *
8904     * @param message used as message if SecurityException is thrown
8905     * @throws SecurityException if the caller is not system or root
8906     */
8907    private static final void enforceSystemOrRoot(String message) {
8908        final int uid = Binder.getCallingUid();
8909        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8910            throw new SecurityException(message);
8911        }
8912    }
8913
8914    @Override
8915    public void performFstrimIfNeeded() {
8916        enforceSystemOrRoot("Only the system can request fstrim");
8917
8918        // Before everything else, see whether we need to fstrim.
8919        try {
8920            IStorageManager sm = PackageHelper.getStorageManager();
8921            if (sm != null) {
8922                boolean doTrim = false;
8923                final long interval = android.provider.Settings.Global.getLong(
8924                        mContext.getContentResolver(),
8925                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8926                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8927                if (interval > 0) {
8928                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8929                    if (timeSinceLast > interval) {
8930                        doTrim = true;
8931                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8932                                + "; running immediately");
8933                    }
8934                }
8935                if (doTrim) {
8936                    final boolean dexOptDialogShown;
8937                    synchronized (mPackages) {
8938                        dexOptDialogShown = mDexOptDialogShown;
8939                    }
8940                    if (!isFirstBoot() && dexOptDialogShown) {
8941                        try {
8942                            ActivityManager.getService().showBootMessage(
8943                                    mContext.getResources().getString(
8944                                            R.string.android_upgrading_fstrim), true);
8945                        } catch (RemoteException e) {
8946                        }
8947                    }
8948                    sm.runMaintenance();
8949                }
8950            } else {
8951                Slog.e(TAG, "storageManager service unavailable!");
8952            }
8953        } catch (RemoteException e) {
8954            // Can't happen; StorageManagerService is local
8955        }
8956    }
8957
8958    @Override
8959    public void updatePackagesIfNeeded() {
8960        enforceSystemOrRoot("Only the system can request package update");
8961
8962        // We need to re-extract after an OTA.
8963        boolean causeUpgrade = isUpgrade();
8964
8965        // First boot or factory reset.
8966        // Note: we also handle devices that are upgrading to N right now as if it is their
8967        //       first boot, as they do not have profile data.
8968        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8969
8970        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8971        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8972
8973        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8974            return;
8975        }
8976
8977        List<PackageParser.Package> pkgs;
8978        synchronized (mPackages) {
8979            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8980        }
8981
8982        final long startTime = System.nanoTime();
8983        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8984                    causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
8985                    false /* bootComplete */);
8986
8987        final int elapsedTimeSeconds =
8988                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8989
8990        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8991        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8992        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8993        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8994        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8995    }
8996
8997    /*
8998     * Return the prebuilt profile path given a package base code path.
8999     */
9000    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9001        return pkg.baseCodePath + ".prof";
9002    }
9003
9004    /**
9005     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9006     * containing statistics about the invocation. The array consists of three elements,
9007     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9008     * and {@code numberOfPackagesFailed}.
9009     */
9010    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9011            final int compilationReason, boolean bootComplete) {
9012
9013        int numberOfPackagesVisited = 0;
9014        int numberOfPackagesOptimized = 0;
9015        int numberOfPackagesSkipped = 0;
9016        int numberOfPackagesFailed = 0;
9017        final int numberOfPackagesToDexopt = pkgs.size();
9018
9019        for (PackageParser.Package pkg : pkgs) {
9020            numberOfPackagesVisited++;
9021
9022            boolean useProfileForDexopt = false;
9023
9024            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9025                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9026                // that are already compiled.
9027                File profileFile = new File(getPrebuildProfilePath(pkg));
9028                // Copy profile if it exists.
9029                if (profileFile.exists()) {
9030                    try {
9031                        // We could also do this lazily before calling dexopt in
9032                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9033                        // is that we don't have a good way to say "do this only once".
9034                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9035                                pkg.applicationInfo.uid, pkg.packageName,
9036                                ArtManager.getProfileName(null))) {
9037                            Log.e(TAG, "Installer failed to copy system profile!");
9038                        } else {
9039                            // Disabled as this causes speed-profile compilation during first boot
9040                            // even if things are already compiled.
9041                            // useProfileForDexopt = true;
9042                        }
9043                    } catch (Exception e) {
9044                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9045                                e);
9046                    }
9047                } else {
9048                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9049                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
9050                    // minimize the number off apps being speed-profile compiled during first boot.
9051                    // The other paths will not change the filter.
9052                    if (disabledPs != null && disabledPs.pkg.isStub) {
9053                        // The package is the stub one, remove the stub suffix to get the normal
9054                        // package and APK names.
9055                        String systemProfilePath =
9056                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
9057                        profileFile = new File(systemProfilePath);
9058                        // If we have a profile for a compressed APK, copy it to the reference
9059                        // location.
9060                        // Note that copying the profile here will cause it to override the
9061                        // reference profile every OTA even though the existing reference profile
9062                        // may have more data. We can't copy during decompression since the
9063                        // directories are not set up at that point.
9064                        if (profileFile.exists()) {
9065                            try {
9066                                // We could also do this lazily before calling dexopt in
9067                                // PackageDexOptimizer to prevent this happening on first boot. The
9068                                // issue is that we don't have a good way to say "do this only
9069                                // once".
9070                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9071                                        pkg.applicationInfo.uid, pkg.packageName,
9072                                        ArtManager.getProfileName(null))) {
9073                                    Log.e(TAG, "Failed to copy system profile for stub package!");
9074                                } else {
9075                                    useProfileForDexopt = true;
9076                                }
9077                            } catch (Exception e) {
9078                                Log.e(TAG, "Failed to copy profile " +
9079                                        profileFile.getAbsolutePath() + " ", e);
9080                            }
9081                        }
9082                    }
9083                }
9084            }
9085
9086            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9087                if (DEBUG_DEXOPT) {
9088                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9089                }
9090                numberOfPackagesSkipped++;
9091                continue;
9092            }
9093
9094            if (DEBUG_DEXOPT) {
9095                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9096                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9097            }
9098
9099            if (showDialog) {
9100                try {
9101                    ActivityManager.getService().showBootMessage(
9102                            mContext.getResources().getString(R.string.android_upgrading_apk,
9103                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9104                } catch (RemoteException e) {
9105                }
9106                synchronized (mPackages) {
9107                    mDexOptDialogShown = true;
9108                }
9109            }
9110
9111            int pkgCompilationReason = compilationReason;
9112            if (useProfileForDexopt) {
9113                // Use background dexopt mode to try and use the profile. Note that this does not
9114                // guarantee usage of the profile.
9115                pkgCompilationReason = PackageManagerService.REASON_BACKGROUND_DEXOPT;
9116            }
9117
9118            // checkProfiles is false to avoid merging profiles during boot which
9119            // might interfere with background compilation (b/28612421).
9120            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9121            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9122            // trade-off worth doing to save boot time work.
9123            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9124            if (compilationReason == REASON_FIRST_BOOT) {
9125                // TODO: This doesn't cover the upgrade case, we should check for this too.
9126                dexoptFlags |= DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE;
9127            }
9128            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9129                    pkg.packageName,
9130                    pkgCompilationReason,
9131                    dexoptFlags));
9132
9133            switch (primaryDexOptStaus) {
9134                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9135                    numberOfPackagesOptimized++;
9136                    break;
9137                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9138                    numberOfPackagesSkipped++;
9139                    break;
9140                case PackageDexOptimizer.DEX_OPT_FAILED:
9141                    numberOfPackagesFailed++;
9142                    break;
9143                default:
9144                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9145                    break;
9146            }
9147        }
9148
9149        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9150                numberOfPackagesFailed };
9151    }
9152
9153    @Override
9154    public void notifyPackageUse(String packageName, int reason) {
9155        synchronized (mPackages) {
9156            final int callingUid = Binder.getCallingUid();
9157            final int callingUserId = UserHandle.getUserId(callingUid);
9158            if (getInstantAppPackageName(callingUid) != null) {
9159                if (!isCallerSameApp(packageName, callingUid)) {
9160                    return;
9161                }
9162            } else {
9163                if (isInstantApp(packageName, callingUserId)) {
9164                    return;
9165                }
9166            }
9167            notifyPackageUseLocked(packageName, reason);
9168        }
9169    }
9170
9171    @GuardedBy("mPackages")
9172    private void notifyPackageUseLocked(String packageName, int reason) {
9173        final PackageParser.Package p = mPackages.get(packageName);
9174        if (p == null) {
9175            return;
9176        }
9177        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9178    }
9179
9180    @Override
9181    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9182            List<String> classPaths, String loaderIsa) {
9183        int userId = UserHandle.getCallingUserId();
9184        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9185        if (ai == null) {
9186            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9187                + loadingPackageName + ", user=" + userId);
9188            return;
9189        }
9190        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9191    }
9192
9193    @Override
9194    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9195            IDexModuleRegisterCallback callback) {
9196        int userId = UserHandle.getCallingUserId();
9197        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9198        DexManager.RegisterDexModuleResult result;
9199        if (ai == null) {
9200            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9201                     " calling user. package=" + packageName + ", user=" + userId);
9202            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9203        } else {
9204            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9205        }
9206
9207        if (callback != null) {
9208            mHandler.post(() -> {
9209                try {
9210                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9211                } catch (RemoteException e) {
9212                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9213                }
9214            });
9215        }
9216    }
9217
9218    /**
9219     * Ask the package manager to perform a dex-opt with the given compiler filter.
9220     *
9221     * Note: exposed only for the shell command to allow moving packages explicitly to a
9222     *       definite state.
9223     */
9224    @Override
9225    public boolean performDexOptMode(String packageName,
9226            boolean checkProfiles, String targetCompilerFilter, boolean force,
9227            boolean bootComplete, String splitName) {
9228        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9229                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9230                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9231        return performDexOpt(new DexoptOptions(packageName, REASON_UNKNOWN,
9232                targetCompilerFilter, splitName, flags));
9233    }
9234
9235    /**
9236     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9237     * secondary dex files belonging to the given package.
9238     *
9239     * Note: exposed only for the shell command to allow moving packages explicitly to a
9240     *       definite state.
9241     */
9242    @Override
9243    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9244            boolean force) {
9245        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9246                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9247                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9248                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9249        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9250    }
9251
9252    /*package*/ boolean performDexOpt(DexoptOptions options) {
9253        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9254            return false;
9255        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9256            return false;
9257        }
9258
9259        if (options.isDexoptOnlySecondaryDex()) {
9260            return mDexManager.dexoptSecondaryDex(options);
9261        } else {
9262            int dexoptStatus = performDexOptWithStatus(options);
9263            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9264        }
9265    }
9266
9267    /**
9268     * Perform dexopt on the given package and return one of following result:
9269     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9270     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9271     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9272     */
9273    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9274        return performDexOptTraced(options);
9275    }
9276
9277    private int performDexOptTraced(DexoptOptions options) {
9278        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9279        try {
9280            return performDexOptInternal(options);
9281        } finally {
9282            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9283        }
9284    }
9285
9286    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9287    // if the package can now be considered up to date for the given filter.
9288    private int performDexOptInternal(DexoptOptions options) {
9289        PackageParser.Package p;
9290        synchronized (mPackages) {
9291            p = mPackages.get(options.getPackageName());
9292            if (p == null) {
9293                // Package could not be found. Report failure.
9294                return PackageDexOptimizer.DEX_OPT_FAILED;
9295            }
9296            mPackageUsage.maybeWriteAsync(mPackages);
9297            mCompilerStats.maybeWriteAsync();
9298        }
9299        long callingId = Binder.clearCallingIdentity();
9300        try {
9301            synchronized (mInstallLock) {
9302                return performDexOptInternalWithDependenciesLI(p, options);
9303            }
9304        } finally {
9305            Binder.restoreCallingIdentity(callingId);
9306        }
9307    }
9308
9309    public ArraySet<String> getOptimizablePackages() {
9310        ArraySet<String> pkgs = new ArraySet<String>();
9311        synchronized (mPackages) {
9312            for (PackageParser.Package p : mPackages.values()) {
9313                if (PackageDexOptimizer.canOptimizePackage(p)) {
9314                    pkgs.add(p.packageName);
9315                }
9316            }
9317        }
9318        return pkgs;
9319    }
9320
9321    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9322            DexoptOptions options) {
9323        // Select the dex optimizer based on the force parameter.
9324        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9325        //       allocate an object here.
9326        PackageDexOptimizer pdo = options.isForce()
9327                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9328                : mPackageDexOptimizer;
9329
9330        // Dexopt all dependencies first. Note: we ignore the return value and march on
9331        // on errors.
9332        // Note that we are going to call performDexOpt on those libraries as many times as
9333        // they are referenced in packages. When we do a batch of performDexOpt (for example
9334        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9335        // and the first package that uses the library will dexopt it. The
9336        // others will see that the compiled code for the library is up to date.
9337        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9338        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9339        if (!deps.isEmpty()) {
9340            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9341                    options.getCompilationReason(), options.getCompilerFilter(),
9342                    options.getSplitName(),
9343                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9344            for (PackageParser.Package depPackage : deps) {
9345                // TODO: Analyze and investigate if we (should) profile libraries.
9346                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9347                        getOrCreateCompilerPackageStats(depPackage),
9348                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9349            }
9350        }
9351        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9352                getOrCreateCompilerPackageStats(p),
9353                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9354    }
9355
9356    /**
9357     * Reconcile the information we have about the secondary dex files belonging to
9358     * {@code packagName} and the actual dex files. For all dex files that were
9359     * deleted, update the internal records and delete the generated oat files.
9360     */
9361    @Override
9362    public void reconcileSecondaryDexFiles(String packageName) {
9363        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9364            return;
9365        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9366            return;
9367        }
9368        mDexManager.reconcileSecondaryDexFiles(packageName);
9369    }
9370
9371    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9372    // a reference there.
9373    /*package*/ DexManager getDexManager() {
9374        return mDexManager;
9375    }
9376
9377    /**
9378     * Execute the background dexopt job immediately.
9379     */
9380    @Override
9381    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9382        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9383            return false;
9384        }
9385        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9386    }
9387
9388    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9389        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9390                || p.usesStaticLibraries != null) {
9391            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9392            Set<String> collectedNames = new HashSet<>();
9393            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9394
9395            retValue.remove(p);
9396
9397            return retValue;
9398        } else {
9399            return Collections.emptyList();
9400        }
9401    }
9402
9403    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9404            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9405        if (!collectedNames.contains(p.packageName)) {
9406            collectedNames.add(p.packageName);
9407            collected.add(p);
9408
9409            if (p.usesLibraries != null) {
9410                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9411                        null, collected, collectedNames);
9412            }
9413            if (p.usesOptionalLibraries != null) {
9414                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9415                        null, collected, collectedNames);
9416            }
9417            if (p.usesStaticLibraries != null) {
9418                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9419                        p.usesStaticLibrariesVersions, collected, collectedNames);
9420            }
9421        }
9422    }
9423
9424    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9425            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9426        final int libNameCount = libs.size();
9427        for (int i = 0; i < libNameCount; i++) {
9428            String libName = libs.get(i);
9429            long version = (versions != null && versions.length == libNameCount)
9430                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9431            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9432            if (libPkg != null) {
9433                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9434            }
9435        }
9436    }
9437
9438    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9439        synchronized (mPackages) {
9440            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9441            if (libEntry != null) {
9442                return mPackages.get(libEntry.apk);
9443            }
9444            return null;
9445        }
9446    }
9447
9448    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9449        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9450        if (versionedLib == null) {
9451            return null;
9452        }
9453        return versionedLib.get(version);
9454    }
9455
9456    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9457        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9458                pkg.staticSharedLibName);
9459        if (versionedLib == null) {
9460            return null;
9461        }
9462        long previousLibVersion = -1;
9463        final int versionCount = versionedLib.size();
9464        for (int i = 0; i < versionCount; i++) {
9465            final long libVersion = versionedLib.keyAt(i);
9466            if (libVersion < pkg.staticSharedLibVersion) {
9467                previousLibVersion = Math.max(previousLibVersion, libVersion);
9468            }
9469        }
9470        if (previousLibVersion >= 0) {
9471            return versionedLib.get(previousLibVersion);
9472        }
9473        return null;
9474    }
9475
9476    public void shutdown() {
9477        mPackageUsage.writeNow(mPackages);
9478        mCompilerStats.writeNow();
9479        mDexManager.writePackageDexUsageNow();
9480
9481        // This is the last chance to write out pending restriction settings
9482        synchronized (mPackages) {
9483            if (mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
9484                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
9485                for (int userId : mDirtyUsers) {
9486                    mSettings.writePackageRestrictionsLPr(userId);
9487                }
9488                mDirtyUsers.clear();
9489            }
9490        }
9491    }
9492
9493    @Override
9494    public void dumpProfiles(String packageName) {
9495        PackageParser.Package pkg;
9496        synchronized (mPackages) {
9497            pkg = mPackages.get(packageName);
9498            if (pkg == null) {
9499                throw new IllegalArgumentException("Unknown package: " + packageName);
9500            }
9501        }
9502        /* Only the shell, root, or the app user should be able to dump profiles. */
9503        int callingUid = Binder.getCallingUid();
9504        if (callingUid != Process.SHELL_UID &&
9505            callingUid != Process.ROOT_UID &&
9506            callingUid != pkg.applicationInfo.uid) {
9507            throw new SecurityException("dumpProfiles");
9508        }
9509
9510        synchronized (mInstallLock) {
9511            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9512            mArtManagerService.dumpProfiles(pkg);
9513            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9514        }
9515    }
9516
9517    @Override
9518    public void forceDexOpt(String packageName) {
9519        enforceSystemOrRoot("forceDexOpt");
9520
9521        PackageParser.Package pkg;
9522        synchronized (mPackages) {
9523            pkg = mPackages.get(packageName);
9524            if (pkg == null) {
9525                throw new IllegalArgumentException("Unknown package: " + packageName);
9526            }
9527        }
9528
9529        synchronized (mInstallLock) {
9530            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9531
9532            // Whoever is calling forceDexOpt wants a compiled package.
9533            // Don't use profiles since that may cause compilation to be skipped.
9534            final int res = performDexOptInternalWithDependenciesLI(
9535                    pkg,
9536                    new DexoptOptions(packageName,
9537                            getDefaultCompilerFilter(),
9538                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9539
9540            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9541            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9542                throw new IllegalStateException("Failed to dexopt: " + res);
9543            }
9544        }
9545    }
9546
9547    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9548        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9549            Slog.w(TAG, "Unable to update from " + oldPkg.name
9550                    + " to " + newPkg.packageName
9551                    + ": old package not in system partition");
9552            return false;
9553        } else if (mPackages.get(oldPkg.name) != null) {
9554            Slog.w(TAG, "Unable to update from " + oldPkg.name
9555                    + " to " + newPkg.packageName
9556                    + ": old package still exists");
9557            return false;
9558        }
9559        return true;
9560    }
9561
9562    void removeCodePathLI(File codePath) {
9563        if (codePath.isDirectory()) {
9564            try {
9565                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9566            } catch (InstallerException e) {
9567                Slog.w(TAG, "Failed to remove code path", e);
9568            }
9569        } else {
9570            codePath.delete();
9571        }
9572    }
9573
9574    private int[] resolveUserIds(int userId) {
9575        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9576    }
9577
9578    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9579        if (pkg == null) {
9580            Slog.wtf(TAG, "Package was null!", new Throwable());
9581            return;
9582        }
9583        clearAppDataLeafLIF(pkg, userId, flags);
9584        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9585        for (int i = 0; i < childCount; i++) {
9586            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9587        }
9588
9589        clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
9590    }
9591
9592    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9593        final PackageSetting ps;
9594        synchronized (mPackages) {
9595            ps = mSettings.mPackages.get(pkg.packageName);
9596        }
9597        for (int realUserId : resolveUserIds(userId)) {
9598            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9599            try {
9600                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9601                        ceDataInode);
9602            } catch (InstallerException e) {
9603                Slog.w(TAG, String.valueOf(e));
9604            }
9605        }
9606    }
9607
9608    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9609        if (pkg == null) {
9610            Slog.wtf(TAG, "Package was null!", new Throwable());
9611            return;
9612        }
9613        destroyAppDataLeafLIF(pkg, userId, flags);
9614        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9615        for (int i = 0; i < childCount; i++) {
9616            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9617        }
9618    }
9619
9620    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9621        final PackageSetting ps;
9622        synchronized (mPackages) {
9623            ps = mSettings.mPackages.get(pkg.packageName);
9624        }
9625        for (int realUserId : resolveUserIds(userId)) {
9626            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9627            try {
9628                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9629                        ceDataInode);
9630            } catch (InstallerException e) {
9631                Slog.w(TAG, String.valueOf(e));
9632            }
9633            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9634        }
9635    }
9636
9637    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9638        if (pkg == null) {
9639            Slog.wtf(TAG, "Package was null!", new Throwable());
9640            return;
9641        }
9642        destroyAppProfilesLeafLIF(pkg);
9643        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9644        for (int i = 0; i < childCount; i++) {
9645            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9646        }
9647    }
9648
9649    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9650        try {
9651            mInstaller.destroyAppProfiles(pkg.packageName);
9652        } catch (InstallerException e) {
9653            Slog.w(TAG, String.valueOf(e));
9654        }
9655    }
9656
9657    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9658        if (pkg == null) {
9659            Slog.wtf(TAG, "Package was null!", new Throwable());
9660            return;
9661        }
9662        mArtManagerService.clearAppProfiles(pkg);
9663        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9664        for (int i = 0; i < childCount; i++) {
9665            mArtManagerService.clearAppProfiles(pkg.childPackages.get(i));
9666        }
9667    }
9668
9669    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9670            long lastUpdateTime) {
9671        // Set parent install/update time
9672        PackageSetting ps = (PackageSetting) pkg.mExtras;
9673        if (ps != null) {
9674            ps.firstInstallTime = firstInstallTime;
9675            ps.lastUpdateTime = lastUpdateTime;
9676        }
9677        // Set children install/update time
9678        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9679        for (int i = 0; i < childCount; i++) {
9680            PackageParser.Package childPkg = pkg.childPackages.get(i);
9681            ps = (PackageSetting) childPkg.mExtras;
9682            if (ps != null) {
9683                ps.firstInstallTime = firstInstallTime;
9684                ps.lastUpdateTime = lastUpdateTime;
9685            }
9686        }
9687    }
9688
9689    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9690            SharedLibraryEntry file,
9691            PackageParser.Package changingLib) {
9692        if (file.path != null) {
9693            usesLibraryFiles.add(file.path);
9694            return;
9695        }
9696        PackageParser.Package p = mPackages.get(file.apk);
9697        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9698            // If we are doing this while in the middle of updating a library apk,
9699            // then we need to make sure to use that new apk for determining the
9700            // dependencies here.  (We haven't yet finished committing the new apk
9701            // to the package manager state.)
9702            if (p == null || p.packageName.equals(changingLib.packageName)) {
9703                p = changingLib;
9704            }
9705        }
9706        if (p != null) {
9707            usesLibraryFiles.addAll(p.getAllCodePaths());
9708            if (p.usesLibraryFiles != null) {
9709                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9710            }
9711        }
9712    }
9713
9714    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9715            PackageParser.Package changingLib) throws PackageManagerException {
9716        if (pkg == null) {
9717            return;
9718        }
9719        // The collection used here must maintain the order of addition (so
9720        // that libraries are searched in the correct order) and must have no
9721        // duplicates.
9722        Set<String> usesLibraryFiles = null;
9723        if (pkg.usesLibraries != null) {
9724            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9725                    null, null, pkg.packageName, changingLib, true,
9726                    pkg.applicationInfo.targetSdkVersion, null);
9727        }
9728        if (pkg.usesStaticLibraries != null) {
9729            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9730                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9731                    pkg.packageName, changingLib, true,
9732                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9733        }
9734        if (pkg.usesOptionalLibraries != null) {
9735            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9736                    null, null, pkg.packageName, changingLib, false,
9737                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9738        }
9739        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9740            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9741        } else {
9742            pkg.usesLibraryFiles = null;
9743        }
9744    }
9745
9746    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9747            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9748            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9749            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9750            throws PackageManagerException {
9751        final int libCount = requestedLibraries.size();
9752        for (int i = 0; i < libCount; i++) {
9753            final String libName = requestedLibraries.get(i);
9754            final long libVersion = requiredVersions != null ? requiredVersions[i]
9755                    : SharedLibraryInfo.VERSION_UNDEFINED;
9756            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9757            if (libEntry == null) {
9758                if (required) {
9759                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9760                            "Package " + packageName + " requires unavailable shared library "
9761                                    + libName + "; failing!");
9762                } else if (DEBUG_SHARED_LIBRARIES) {
9763                    Slog.i(TAG, "Package " + packageName
9764                            + " desires unavailable shared library "
9765                            + libName + "; ignoring!");
9766                }
9767            } else {
9768                if (requiredVersions != null && requiredCertDigests != null) {
9769                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9770                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9771                            "Package " + packageName + " requires unavailable static shared"
9772                                    + " library " + libName + " version "
9773                                    + libEntry.info.getLongVersion() + "; failing!");
9774                    }
9775
9776                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9777                    if (libPkg == null) {
9778                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9779                                "Package " + packageName + " requires unavailable static shared"
9780                                        + " library; failing!");
9781                    }
9782
9783                    final String[] expectedCertDigests = requiredCertDigests[i];
9784
9785
9786                    if (expectedCertDigests.length > 1) {
9787
9788                        // For apps targeting O MR1 we require explicit enumeration of all certs.
9789                        final String[] libCertDigests = (targetSdk >= Build.VERSION_CODES.O_MR1)
9790                                ? PackageUtils.computeSignaturesSha256Digests(
9791                                libPkg.mSigningDetails.signatures)
9792                                : PackageUtils.computeSignaturesSha256Digests(
9793                                        new Signature[]{libPkg.mSigningDetails.signatures[0]});
9794
9795                        // Take a shortcut if sizes don't match. Note that if an app doesn't
9796                        // target O we don't parse the "additional-certificate" tags similarly
9797                        // how we only consider all certs only for apps targeting O (see above).
9798                        // Therefore, the size check is safe to make.
9799                        if (expectedCertDigests.length != libCertDigests.length) {
9800                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9801                                    "Package " + packageName + " requires differently signed" +
9802                                            " static shared library; failing!");
9803                        }
9804
9805                        // Use a predictable order as signature order may vary
9806                        Arrays.sort(libCertDigests);
9807                        Arrays.sort(expectedCertDigests);
9808
9809                        final int certCount = libCertDigests.length;
9810                        for (int j = 0; j < certCount; j++) {
9811                            if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9812                                throw new PackageManagerException(
9813                                        INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9814                                        "Package " + packageName + " requires differently signed" +
9815                                                " static shared library; failing!");
9816                            }
9817                        }
9818                    } else {
9819
9820                        // lib signing cert could have rotated beyond the one expected, check to see
9821                        // if the new one has been blessed by the old
9822                        if (!libPkg.mSigningDetails.hasSha256Certificate(
9823                                ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) {
9824                            throw new PackageManagerException(
9825                                    INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9826                                    "Package " + packageName + " requires differently signed" +
9827                                            " static shared library; failing!");
9828                        }
9829                    }
9830                }
9831
9832                if (outUsedLibraries == null) {
9833                    // Use LinkedHashSet to preserve the order of files added to
9834                    // usesLibraryFiles while eliminating duplicates.
9835                    outUsedLibraries = new LinkedHashSet<>();
9836                }
9837                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9838            }
9839        }
9840        return outUsedLibraries;
9841    }
9842
9843    private static boolean hasString(List<String> list, List<String> which) {
9844        if (list == null) {
9845            return false;
9846        }
9847        for (int i=list.size()-1; i>=0; i--) {
9848            for (int j=which.size()-1; j>=0; j--) {
9849                if (which.get(j).equals(list.get(i))) {
9850                    return true;
9851                }
9852            }
9853        }
9854        return false;
9855    }
9856
9857    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9858            PackageParser.Package changingPkg) {
9859        ArrayList<PackageParser.Package> res = null;
9860        for (PackageParser.Package pkg : mPackages.values()) {
9861            if (changingPkg != null
9862                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9863                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9864                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9865                            changingPkg.staticSharedLibName)) {
9866                return null;
9867            }
9868            if (res == null) {
9869                res = new ArrayList<>();
9870            }
9871            res.add(pkg);
9872            try {
9873                updateSharedLibrariesLPr(pkg, changingPkg);
9874            } catch (PackageManagerException e) {
9875                // If a system app update or an app and a required lib missing we
9876                // delete the package and for updated system apps keep the data as
9877                // it is better for the user to reinstall than to be in an limbo
9878                // state. Also libs disappearing under an app should never happen
9879                // - just in case.
9880                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9881                    final int flags = pkg.isUpdatedSystemApp()
9882                            ? PackageManager.DELETE_KEEP_DATA : 0;
9883                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9884                            flags , null, true, null);
9885                }
9886                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9887            }
9888        }
9889        return res;
9890    }
9891
9892    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9893            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9894            @Nullable UserHandle user) throws PackageManagerException {
9895        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9896        // If the package has children and this is the first dive in the function
9897        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9898        // whether all packages (parent and children) would be successfully scanned
9899        // before the actual scan since scanning mutates internal state and we want
9900        // to atomically install the package and its children.
9901        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9902            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9903                scanFlags |= SCAN_CHECK_ONLY;
9904            }
9905        } else {
9906            scanFlags &= ~SCAN_CHECK_ONLY;
9907        }
9908
9909        final PackageParser.Package scannedPkg;
9910        try {
9911            // Scan the parent
9912            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9913            // Scan the children
9914            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9915            for (int i = 0; i < childCount; i++) {
9916                PackageParser.Package childPkg = pkg.childPackages.get(i);
9917                scanPackageNewLI(childPkg, parseFlags,
9918                        scanFlags, currentTime, user);
9919            }
9920        } finally {
9921            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9922        }
9923
9924        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9925            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9926        }
9927
9928        return scannedPkg;
9929    }
9930
9931    /** The result of a package scan. */
9932    private static class ScanResult {
9933        /** Whether or not the package scan was successful */
9934        public final boolean success;
9935        /**
9936         * The final package settings. This may be the same object passed in
9937         * the {@link ScanRequest}, but, with modified values.
9938         */
9939        @Nullable public final PackageSetting pkgSetting;
9940        /** ABI code paths that have changed in the package scan */
9941        @Nullable public final List<String> changedAbiCodePath;
9942        public ScanResult(
9943                boolean success,
9944                @Nullable PackageSetting pkgSetting,
9945                @Nullable List<String> changedAbiCodePath) {
9946            this.success = success;
9947            this.pkgSetting = pkgSetting;
9948            this.changedAbiCodePath = changedAbiCodePath;
9949        }
9950    }
9951
9952    /** A package to be scanned */
9953    private static class ScanRequest {
9954        /** The parsed package */
9955        @NonNull public final PackageParser.Package pkg;
9956        /** The package this package replaces */
9957        @Nullable public final PackageParser.Package oldPkg;
9958        /** Shared user settings, if the package has a shared user */
9959        @Nullable public final SharedUserSetting sharedUserSetting;
9960        /**
9961         * Package settings of the currently installed version.
9962         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9963         * during scan.
9964         */
9965        @Nullable public final PackageSetting pkgSetting;
9966        /** A copy of the settings for the currently installed version */
9967        @Nullable public final PackageSetting oldPkgSetting;
9968        /** Package settings for the disabled version on the /system partition */
9969        @Nullable public final PackageSetting disabledPkgSetting;
9970        /** Package settings for the installed version under its original package name */
9971        @Nullable public final PackageSetting originalPkgSetting;
9972        /** The real package name of a renamed application */
9973        @Nullable public final String realPkgName;
9974        public final @ParseFlags int parseFlags;
9975        public final @ScanFlags int scanFlags;
9976        /** The user for which the package is being scanned */
9977        @Nullable public final UserHandle user;
9978        /** Whether or not the platform package is being scanned */
9979        public final boolean isPlatformPackage;
9980        public ScanRequest(
9981                @NonNull PackageParser.Package pkg,
9982                @Nullable SharedUserSetting sharedUserSetting,
9983                @Nullable PackageParser.Package oldPkg,
9984                @Nullable PackageSetting pkgSetting,
9985                @Nullable PackageSetting disabledPkgSetting,
9986                @Nullable PackageSetting originalPkgSetting,
9987                @Nullable String realPkgName,
9988                @ParseFlags int parseFlags,
9989                @ScanFlags int scanFlags,
9990                boolean isPlatformPackage,
9991                @Nullable UserHandle user) {
9992            this.pkg = pkg;
9993            this.oldPkg = oldPkg;
9994            this.pkgSetting = pkgSetting;
9995            this.sharedUserSetting = sharedUserSetting;
9996            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9997            this.disabledPkgSetting = disabledPkgSetting;
9998            this.originalPkgSetting = originalPkgSetting;
9999            this.realPkgName = realPkgName;
10000            this.parseFlags = parseFlags;
10001            this.scanFlags = scanFlags;
10002            this.isPlatformPackage = isPlatformPackage;
10003            this.user = user;
10004        }
10005    }
10006
10007    /**
10008     * Returns the actual scan flags depending upon the state of the other settings.
10009     * <p>Updated system applications will not have the following flags set
10010     * by default and need to be adjusted after the fact:
10011     * <ul>
10012     * <li>{@link #SCAN_AS_SYSTEM}</li>
10013     * <li>{@link #SCAN_AS_PRIVILEGED}</li>
10014     * <li>{@link #SCAN_AS_OEM}</li>
10015     * <li>{@link #SCAN_AS_VENDOR}</li>
10016     * <li>{@link #SCAN_AS_PRODUCT}</li>
10017     * <li>{@link #SCAN_AS_INSTANT_APP}</li>
10018     * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li>
10019     * </ul>
10020     */
10021    private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags,
10022            PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user,
10023            PackageParser.Package pkg) {
10024        if (disabledPkgSetting != null) {
10025            // updated system application, must at least have SCAN_AS_SYSTEM
10026            scanFlags |= SCAN_AS_SYSTEM;
10027            if ((disabledPkgSetting.pkgPrivateFlags
10028                    & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
10029                scanFlags |= SCAN_AS_PRIVILEGED;
10030            }
10031            if ((disabledPkgSetting.pkgPrivateFlags
10032                    & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
10033                scanFlags |= SCAN_AS_OEM;
10034            }
10035            if ((disabledPkgSetting.pkgPrivateFlags
10036                    & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
10037                scanFlags |= SCAN_AS_VENDOR;
10038            }
10039            if ((disabledPkgSetting.pkgPrivateFlags
10040                    & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) {
10041                scanFlags |= SCAN_AS_PRODUCT;
10042            }
10043        }
10044        if (pkgSetting != null) {
10045            final int userId = ((user == null) ? 0 : user.getIdentifier());
10046            if (pkgSetting.getInstantApp(userId)) {
10047                scanFlags |= SCAN_AS_INSTANT_APP;
10048            }
10049            if (pkgSetting.getVirtulalPreload(userId)) {
10050                scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
10051            }
10052        }
10053
10054        // Scan as privileged apps that share a user with a priv-app.
10055        final boolean skipVendorPrivilegeScan = ((scanFlags & SCAN_AS_VENDOR) != 0)
10056                && SystemProperties.getInt("ro.vndk.version", 28) < 28;
10057        if (((scanFlags & SCAN_AS_PRIVILEGED) == 0)
10058                && !pkg.isPrivileged()
10059                && (pkg.mSharedUserId != null)
10060                && !skipVendorPrivilegeScan) {
10061            SharedUserSetting sharedUserSetting = null;
10062            try {
10063                sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
10064            } catch (PackageManagerException ignore) {}
10065            if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
10066                // Exempt SharedUsers signed with the platform key.
10067                // TODO(b/72378145) Fix this exemption. Force signature apps
10068                // to whitelist their privileged permissions just like other
10069                // priv-apps.
10070                synchronized (mPackages) {
10071                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
10072                    if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
10073                                pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
10074                        scanFlags |= SCAN_AS_PRIVILEGED;
10075                    }
10076                }
10077            }
10078        }
10079
10080        return scanFlags;
10081    }
10082
10083    // TODO: scanPackageNewLI() and scanPackageOnly() should be merged. But, first, commiting
10084    // the results / removing app data needs to be moved up a level to the callers of this
10085    // method. Also, we need to solve the problem of potentially creating a new shared user
10086    // setting. That can probably be done later and patch things up after the fact.
10087    @GuardedBy("mInstallLock")
10088    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
10089            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
10090            @Nullable UserHandle user) throws PackageManagerException {
10091
10092        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10093        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
10094        if (realPkgName != null) {
10095            ensurePackageRenamed(pkg, renamedPkgName);
10096        }
10097        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
10098        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10099        final PackageSetting disabledPkgSetting =
10100                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10101
10102        if (mTransferedPackages.contains(pkg.packageName)) {
10103            Slog.w(TAG, "Package " + pkg.packageName
10104                    + " was transferred to another, but its .apk remains");
10105        }
10106
10107        scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg);
10108        synchronized (mPackages) {
10109            applyPolicy(pkg, parseFlags, scanFlags, mPlatformPackage);
10110            assertPackageIsValid(pkg, parseFlags, scanFlags);
10111
10112            SharedUserSetting sharedUserSetting = null;
10113            if (pkg.mSharedUserId != null) {
10114                // SIDE EFFECTS; may potentially allocate a new shared user
10115                sharedUserSetting = mSettings.getSharedUserLPw(
10116                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10117                if (DEBUG_PACKAGE_SCANNING) {
10118                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10119                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
10120                                + " (uid=" + sharedUserSetting.userId + "):"
10121                                + " packages=" + sharedUserSetting.packages);
10122                }
10123            }
10124
10125            boolean scanSucceeded = false;
10126            try {
10127                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
10128                        pkgSetting == null ? null : pkgSetting.pkg, pkgSetting, disabledPkgSetting,
10129                        originalPkgSetting, realPkgName, parseFlags, scanFlags,
10130                        (pkg == mPlatformPackage), user);
10131                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
10132                if (result.success) {
10133                    commitScanResultsLocked(request, result);
10134                }
10135                scanSucceeded = true;
10136            } finally {
10137                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10138                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
10139                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10140                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10141                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10142                  }
10143            }
10144        }
10145        return pkg;
10146    }
10147
10148    /**
10149     * Commits the package scan and modifies system state.
10150     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
10151     * of committing the package, leaving the system in an inconsistent state.
10152     * This needs to be fixed so, once we get to this point, no errors are
10153     * possible and the system is not left in an inconsistent state.
10154     */
10155    @GuardedBy("mPackages")
10156    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
10157            throws PackageManagerException {
10158        final PackageParser.Package pkg = request.pkg;
10159        final PackageParser.Package oldPkg = request.oldPkg;
10160        final @ParseFlags int parseFlags = request.parseFlags;
10161        final @ScanFlags int scanFlags = request.scanFlags;
10162        final PackageSetting oldPkgSetting = request.oldPkgSetting;
10163        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10164        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10165        final UserHandle user = request.user;
10166        final String realPkgName = request.realPkgName;
10167        final PackageSetting pkgSetting = result.pkgSetting;
10168        final List<String> changedAbiCodePath = result.changedAbiCodePath;
10169        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
10170
10171        if (newPkgSettingCreated) {
10172            if (originalPkgSetting != null) {
10173                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
10174            }
10175            // THROWS: when we can't allocate a user id. add call to check if there's
10176            // enough space to ensure we won't throw; otherwise, don't modify state
10177            mSettings.addUserToSettingLPw(pkgSetting);
10178
10179            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
10180                mTransferedPackages.add(originalPkgSetting.name);
10181            }
10182        }
10183        // TODO(toddke): Consider a method specifically for modifying the Package object
10184        // post scan; or, moving this stuff out of the Package object since it has nothing
10185        // to do with the package on disk.
10186        // We need to have this here because addUserToSettingLPw() is sometimes responsible
10187        // for creating the application ID. If we did this earlier, we would be saving the
10188        // correct ID.
10189        pkg.applicationInfo.uid = pkgSetting.appId;
10190
10191        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10192
10193        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
10194            mTransferedPackages.add(pkg.packageName);
10195        }
10196
10197        // THROWS: when requested libraries that can't be found. it only changes
10198        // the state of the passed in pkg object, so, move to the top of the method
10199        // and allow it to abort
10200        if ((scanFlags & SCAN_BOOTING) == 0
10201                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10202            // Check all shared libraries and map to their actual file path.
10203            // We only do this here for apps not on a system dir, because those
10204            // are the only ones that can fail an install due to this.  We
10205            // will take care of the system apps by updating all of their
10206            // library paths after the scan is done. Also during the initial
10207            // scan don't update any libs as we do this wholesale after all
10208            // apps are scanned to avoid dependency based scanning.
10209            updateSharedLibrariesLPr(pkg, null);
10210        }
10211
10212        // All versions of a static shared library are referenced with the same
10213        // package name. Internally, we use a synthetic package name to allow
10214        // multiple versions of the same shared library to be installed. So,
10215        // we need to generate the synthetic package name of the latest shared
10216        // library in order to compare signatures.
10217        PackageSetting signatureCheckPs = pkgSetting;
10218        if (pkg.applicationInfo.isStaticSharedLibrary()) {
10219            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10220            if (libraryEntry != null) {
10221                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10222            }
10223        }
10224
10225        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10226        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
10227            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
10228                // We just determined the app is signed correctly, so bring
10229                // over the latest parsed certs.
10230                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10231            } else {
10232                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10233                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10234                            "Package " + pkg.packageName + " upgrade keys do not match the "
10235                                    + "previously installed version");
10236                } else {
10237                    pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10238                    String msg = "System package " + pkg.packageName
10239                            + " signature changed; retaining data.";
10240                    reportSettingsProblem(Log.WARN, msg);
10241                }
10242            }
10243        } else {
10244            try {
10245                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
10246                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
10247                final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting,
10248                        pkg.mSigningDetails, compareCompat, compareRecover);
10249                // The new KeySets will be re-added later in the scanning process.
10250                if (compatMatch) {
10251                    synchronized (mPackages) {
10252                        ksms.removeAppKeySetDataLPw(pkg.packageName);
10253                    }
10254                }
10255                // We just determined the app is signed correctly, so bring
10256                // over the latest parsed certs.
10257                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10258
10259
10260                // if this is is a sharedUser, check to see if the new package is signed by a newer
10261                // signing certificate than the existing one, and if so, copy over the new details
10262                if (signatureCheckPs.sharedUser != null) {
10263                    if (pkg.mSigningDetails.hasAncestor(
10264                                signatureCheckPs.sharedUser.signatures.mSigningDetails)) {
10265                        signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10266                    }
10267                    if (signatureCheckPs.sharedUser.signaturesChanged == null) {
10268                        signatureCheckPs.sharedUser.signaturesChanged = Boolean.FALSE;
10269                    }
10270                }
10271            } catch (PackageManagerException e) {
10272                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10273                    throw e;
10274                }
10275                // The signature has changed, but this package is in the system
10276                // image...  let's recover!
10277                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10278
10279                // If the system app is part of a shared user we allow that shared user to change
10280                // signatures as well as part of an OTA. We still need to verify that the signatures
10281                // are consistent within the shared user for a given boot, so only allow updating
10282                // the signatures on the first package scanned for the shared user (i.e. if the
10283                // signaturesChanged state hasn't been initialized yet in SharedUserSetting).
10284                if (signatureCheckPs.sharedUser != null) {
10285                    if (signatureCheckPs.sharedUser.signaturesChanged != null &&
10286                        compareSignatures(
10287                            signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures,
10288                            pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) {
10289                        throw new PackageManagerException(
10290                                INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10291                                "Signature mismatch for shared user: " + pkgSetting.sharedUser);
10292                    }
10293
10294                    signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10295                    signatureCheckPs.sharedUser.signaturesChanged = Boolean.TRUE;
10296                }
10297                // File a report about this.
10298                String msg = "System package " + pkg.packageName
10299                        + " signature changed; retaining data.";
10300                reportSettingsProblem(Log.WARN, msg);
10301            } catch (IllegalArgumentException e) {
10302
10303                // should never happen: certs matched when checking, but not when comparing
10304                // old to new for sharedUser
10305                throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10306                        "Signing certificates comparison made on incomparable signing details"
10307                        + " but somehow passed verifySignatures!");
10308            }
10309        }
10310
10311        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10312            // This package wants to adopt ownership of permissions from
10313            // another package.
10314            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10315                final String origName = pkg.mAdoptPermissions.get(i);
10316                final PackageSetting orig = mSettings.getPackageLPr(origName);
10317                if (orig != null) {
10318                    if (verifyPackageUpdateLPr(orig, pkg)) {
10319                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
10320                                + pkg.packageName);
10321                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10322                    }
10323                }
10324            }
10325        }
10326
10327        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
10328            for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
10329                final String codePathString = changedAbiCodePath.get(i);
10330                try {
10331                    mInstaller.rmdex(codePathString,
10332                            getDexCodeInstructionSet(getPreferredInstructionSet()));
10333                } catch (InstallerException ignored) {
10334                }
10335            }
10336        }
10337
10338        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10339            if (oldPkgSetting != null) {
10340                synchronized (mPackages) {
10341                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
10342                }
10343            }
10344        } else {
10345            final int userId = user == null ? 0 : user.getIdentifier();
10346            // Modify state for the given package setting
10347            commitPackageSettings(pkg, oldPkg, pkgSetting, user, scanFlags,
10348                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10349            if (pkgSetting.getInstantApp(userId)) {
10350                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10351            }
10352        }
10353    }
10354
10355    /**
10356     * Returns the "real" name of the package.
10357     * <p>This may differ from the package's actual name if the application has already
10358     * been installed under one of this package's original names.
10359     */
10360    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
10361            @Nullable String renamedPkgName) {
10362        if (isPackageRenamed(pkg, renamedPkgName)) {
10363            return pkg.mRealPackage;
10364        }
10365        return null;
10366    }
10367
10368    /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
10369    private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
10370            @Nullable String renamedPkgName) {
10371        return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
10372    }
10373
10374    /**
10375     * Returns the original package setting.
10376     * <p>A package can migrate its name during an update. In this scenario, a package
10377     * designates a set of names that it considers as one of its original names.
10378     * <p>An original package must be signed identically and it must have the same
10379     * shared user [if any].
10380     */
10381    @GuardedBy("mPackages")
10382    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
10383            @Nullable String renamedPkgName) {
10384        if (!isPackageRenamed(pkg, renamedPkgName)) {
10385            return null;
10386        }
10387        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
10388            final PackageSetting originalPs =
10389                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
10390            if (originalPs != null) {
10391                // the package is already installed under its original name...
10392                // but, should we use it?
10393                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
10394                    // the new package is incompatible with the original
10395                    continue;
10396                } else if (originalPs.sharedUser != null) {
10397                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
10398                        // the shared user id is incompatible with the original
10399                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
10400                                + " to " + pkg.packageName + ": old uid "
10401                                + originalPs.sharedUser.name
10402                                + " differs from " + pkg.mSharedUserId);
10403                        continue;
10404                    }
10405                    // TODO: Add case when shared user id is added [b/28144775]
10406                } else {
10407                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10408                            + pkg.packageName + " to old name " + originalPs.name);
10409                }
10410                return originalPs;
10411            }
10412        }
10413        return null;
10414    }
10415
10416    /**
10417     * Renames the package if it was installed under a different name.
10418     * <p>When we've already installed the package under an original name, update
10419     * the new package so we can continue to have the old name.
10420     */
10421    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10422            @NonNull String renamedPackageName) {
10423        if (pkg.mOriginalPackages == null
10424                || !pkg.mOriginalPackages.contains(renamedPackageName)
10425                || pkg.packageName.equals(renamedPackageName)) {
10426            return;
10427        }
10428        pkg.setPackageName(renamedPackageName);
10429    }
10430
10431    /**
10432     * Just scans the package without any side effects.
10433     * <p>Not entirely true at the moment. There is still one side effect -- this
10434     * method potentially modifies a live {@link PackageSetting} object representing
10435     * the package being scanned. This will be resolved in the future.
10436     *
10437     * @param request Information about the package to be scanned
10438     * @param isUnderFactoryTest Whether or not the device is under factory test
10439     * @param currentTime The current time, in millis
10440     * @return The results of the scan
10441     */
10442    @GuardedBy("mInstallLock")
10443    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10444            boolean isUnderFactoryTest, long currentTime)
10445                    throws PackageManagerException {
10446        final PackageParser.Package pkg = request.pkg;
10447        PackageSetting pkgSetting = request.pkgSetting;
10448        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10449        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10450        final @ParseFlags int parseFlags = request.parseFlags;
10451        final @ScanFlags int scanFlags = request.scanFlags;
10452        final String realPkgName = request.realPkgName;
10453        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10454        final UserHandle user = request.user;
10455        final boolean isPlatformPackage = request.isPlatformPackage;
10456
10457        List<String> changedAbiCodePath = null;
10458
10459        if (DEBUG_PACKAGE_SCANNING) {
10460            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10461                Log.d(TAG, "Scanning package " + pkg.packageName);
10462        }
10463
10464        DexManager.maybeLogUnexpectedPackageDetails(pkg);
10465
10466        // Initialize package source and resource directories
10467        final File scanFile = new File(pkg.codePath);
10468        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10469        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10470
10471        // We keep references to the derived CPU Abis from settings in oder to reuse
10472        // them in the case where we're not upgrading or booting for the first time.
10473        String primaryCpuAbiFromSettings = null;
10474        String secondaryCpuAbiFromSettings = null;
10475        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10476
10477        if (!needToDeriveAbi) {
10478            if (pkgSetting != null) {
10479                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10480                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10481            } else {
10482                // Re-scanning a system package after uninstalling updates; need to derive ABI
10483                needToDeriveAbi = true;
10484            }
10485        }
10486
10487        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10488            PackageManagerService.reportSettingsProblem(Log.WARN,
10489                    "Package " + pkg.packageName + " shared user changed from "
10490                            + (pkgSetting.sharedUser != null
10491                            ? pkgSetting.sharedUser.name : "<nothing>")
10492                            + " to "
10493                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10494                            + "; replacing with new");
10495            pkgSetting = null;
10496        }
10497
10498        String[] usesStaticLibraries = null;
10499        if (pkg.usesStaticLibraries != null) {
10500            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10501            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10502        }
10503        final boolean createNewPackage = (pkgSetting == null);
10504        if (createNewPackage) {
10505            final String parentPackageName = (pkg.parentPackage != null)
10506                    ? pkg.parentPackage.packageName : null;
10507            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10508            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10509            // REMOVE SharedUserSetting from method; update in a separate call
10510            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10511                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10512                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10513                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10514                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10515                    user, true /*allowInstall*/, instantApp, virtualPreload,
10516                    parentPackageName, pkg.getChildPackageNames(),
10517                    UserManagerService.getInstance(), usesStaticLibraries,
10518                    pkg.usesStaticLibrariesVersions);
10519        } else {
10520            // REMOVE SharedUserSetting from method; update in a separate call.
10521            //
10522            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10523            // secondaryCpuAbi are not known at this point so we always update them
10524            // to null here, only to reset them at a later point.
10525            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10526                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
10527                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10528                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10529                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10530                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10531        }
10532        if (createNewPackage && originalPkgSetting != null) {
10533            // This is the initial transition from the original package, so,
10534            // fix up the new package's name now. We must do this after looking
10535            // up the package under its new name, so getPackageLP takes care of
10536            // fiddling things correctly.
10537            pkg.setPackageName(originalPkgSetting.name);
10538
10539            // File a report about this.
10540            String msg = "New package " + pkgSetting.realName
10541                    + " renamed to replace old package " + pkgSetting.name;
10542            reportSettingsProblem(Log.WARN, msg);
10543        }
10544
10545        final int userId = (user == null ? UserHandle.USER_SYSTEM : user.getIdentifier());
10546        // for existing packages, change the install state; but, only if it's explicitly specified
10547        if (!createNewPackage) {
10548            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10549            final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
10550            setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
10551        }
10552
10553        if (disabledPkgSetting != null) {
10554            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10555        }
10556
10557        // Apps which share a sharedUserId must be placed in the same selinux domain. If this
10558        // package is the first app installed as this shared user, set seInfoTargetSdkVersion to its
10559        // targetSdkVersion. These are later adjusted in PackageManagerService's constructor to be
10560        // the lowest targetSdkVersion of all apps within the shared user, which corresponds to the
10561        // least restrictive selinux domain.
10562        // NOTE: As new packages are installed / updated, the shared user's seinfoTargetSdkVersion
10563        // will NOT be modified until next boot, even if a lower targetSdkVersion is used. This
10564        // ensures that all packages continue to run in the same selinux domain.
10565        final int targetSdkVersion =
10566            ((sharedUserSetting != null) && (sharedUserSetting.packages.size() != 0)) ?
10567            sharedUserSetting.seInfoTargetSdkVersion : pkg.applicationInfo.targetSdkVersion;
10568        // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync.
10569        // They currently can be if the sharedUser apps are signed with the platform key.
10570        final boolean isPrivileged = (sharedUserSetting != null) ?
10571            sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged();
10572
10573        pkg.applicationInfo.seInfo = SELinuxMMAC.getSeInfo(pkg, isPrivileged,
10574                pkg.applicationInfo.targetSandboxVersion, targetSdkVersion);
10575        pkg.applicationInfo.seInfoUser = SELinuxUtil.assignSeinfoUser(pkgSetting.readUserState(
10576                userId == UserHandle.USER_ALL ? UserHandle.USER_SYSTEM : userId));
10577
10578        pkg.mExtras = pkgSetting;
10579        pkg.applicationInfo.processName = fixProcessName(
10580                pkg.applicationInfo.packageName,
10581                pkg.applicationInfo.processName);
10582
10583        if (!isPlatformPackage) {
10584            // Get all of our default paths setup
10585            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10586        }
10587
10588        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10589
10590        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10591            if (needToDeriveAbi) {
10592                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10593                final boolean extractNativeLibs = !pkg.isLibrary();
10594                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10595                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10596
10597                // Some system apps still use directory structure for native libraries
10598                // in which case we might end up not detecting abi solely based on apk
10599                // structure. Try to detect abi based on directory structure.
10600                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10601                        pkg.applicationInfo.primaryCpuAbi == null) {
10602                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10603                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10604                }
10605            } else {
10606                // This is not a first boot or an upgrade, don't bother deriving the
10607                // ABI during the scan. Instead, trust the value that was stored in the
10608                // package setting.
10609                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10610                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10611
10612                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10613
10614                if (DEBUG_ABI_SELECTION) {
10615                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10616                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10617                            pkg.applicationInfo.secondaryCpuAbi);
10618                }
10619            }
10620        } else {
10621            if ((scanFlags & SCAN_MOVE) != 0) {
10622                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10623                // but we already have this packages package info in the PackageSetting. We just
10624                // use that and derive the native library path based on the new codepath.
10625                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10626                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10627            }
10628
10629            // Set native library paths again. For moves, the path will be updated based on the
10630            // ABIs we've determined above. For non-moves, the path will be updated based on the
10631            // ABIs we determined during compilation, but the path will depend on the final
10632            // package path (after the rename away from the stage path).
10633            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10634        }
10635
10636        // This is a special case for the "system" package, where the ABI is
10637        // dictated by the zygote configuration (and init.rc). We should keep track
10638        // of this ABI so that we can deal with "normal" applications that run under
10639        // the same UID correctly.
10640        if (isPlatformPackage) {
10641            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10642                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10643        }
10644
10645        // If there's a mismatch between the abi-override in the package setting
10646        // and the abiOverride specified for the install. Warn about this because we
10647        // would've already compiled the app without taking the package setting into
10648        // account.
10649        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10650            if (cpuAbiOverride == null && pkg.packageName != null) {
10651                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10652                        " for package " + pkg.packageName);
10653            }
10654        }
10655
10656        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10657        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10658        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10659
10660        // Copy the derived override back to the parsed package, so that we can
10661        // update the package settings accordingly.
10662        pkg.cpuAbiOverride = cpuAbiOverride;
10663
10664        if (DEBUG_ABI_SELECTION) {
10665            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
10666                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10667                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10668        }
10669
10670        // Push the derived path down into PackageSettings so we know what to
10671        // clean up at uninstall time.
10672        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10673
10674        if (DEBUG_ABI_SELECTION) {
10675            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10676                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10677                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10678        }
10679
10680        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10681            // We don't do this here during boot because we can do it all
10682            // at once after scanning all existing packages.
10683            //
10684            // We also do this *before* we perform dexopt on this package, so that
10685            // we can avoid redundant dexopts, and also to make sure we've got the
10686            // code and package path correct.
10687            changedAbiCodePath =
10688                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10689        }
10690
10691        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10692                android.Manifest.permission.FACTORY_TEST)) {
10693            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10694        }
10695
10696        if (isSystemApp(pkg)) {
10697            pkgSetting.isOrphaned = true;
10698        }
10699
10700        // Take care of first install / last update times.
10701        final long scanFileTime = getLastModifiedTime(pkg);
10702        if (currentTime != 0) {
10703            if (pkgSetting.firstInstallTime == 0) {
10704                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10705            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10706                pkgSetting.lastUpdateTime = currentTime;
10707            }
10708        } else if (pkgSetting.firstInstallTime == 0) {
10709            // We need *something*.  Take time time stamp of the file.
10710            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10711        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10712            if (scanFileTime != pkgSetting.timeStamp) {
10713                // A package on the system image has changed; consider this
10714                // to be an update.
10715                pkgSetting.lastUpdateTime = scanFileTime;
10716            }
10717        }
10718        pkgSetting.setTimeStamp(scanFileTime);
10719
10720        pkgSetting.pkg = pkg;
10721        pkgSetting.pkgFlags = pkg.applicationInfo.flags;
10722        if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
10723            pkgSetting.versionCode = pkg.getLongVersionCode();
10724        }
10725        // Update volume if needed
10726        final String volumeUuid = pkg.applicationInfo.volumeUuid;
10727        if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
10728            Slog.i(PackageManagerService.TAG,
10729                    "Update" + (pkgSetting.isSystem() ? " system" : "")
10730                    + " package " + pkg.packageName
10731                    + " volume from " + pkgSetting.volumeUuid
10732                    + " to " + volumeUuid);
10733            pkgSetting.volumeUuid = volumeUuid;
10734        }
10735
10736        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10737    }
10738
10739    /**
10740     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10741     */
10742    private static boolean apkHasCode(String fileName) {
10743        StrictJarFile jarFile = null;
10744        try {
10745            jarFile = new StrictJarFile(fileName,
10746                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10747            return jarFile.findEntry("classes.dex") != null;
10748        } catch (IOException ignore) {
10749        } finally {
10750            try {
10751                if (jarFile != null) {
10752                    jarFile.close();
10753                }
10754            } catch (IOException ignore) {}
10755        }
10756        return false;
10757    }
10758
10759    /**
10760     * Enforces code policy for the package. This ensures that if an APK has
10761     * declared hasCode="true" in its manifest that the APK actually contains
10762     * code.
10763     *
10764     * @throws PackageManagerException If bytecode could not be found when it should exist
10765     */
10766    private static void assertCodePolicy(PackageParser.Package pkg)
10767            throws PackageManagerException {
10768        final boolean shouldHaveCode =
10769                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10770        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10771            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10772                    "Package " + pkg.baseCodePath + " code is missing");
10773        }
10774
10775        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10776            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10777                final boolean splitShouldHaveCode =
10778                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10779                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10780                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10781                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10782                }
10783            }
10784        }
10785    }
10786
10787    /**
10788     * Applies policy to the parsed package based upon the given policy flags.
10789     * Ensures the package is in a good state.
10790     * <p>
10791     * Implementation detail: This method must NOT have any side effect. It would
10792     * ideally be static, but, it requires locks to read system state.
10793     */
10794    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10795            final @ScanFlags int scanFlags, PackageParser.Package platformPkg) {
10796        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10797            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10798            if (pkg.applicationInfo.isDirectBootAware()) {
10799                // we're direct boot aware; set for all components
10800                for (PackageParser.Service s : pkg.services) {
10801                    s.info.encryptionAware = s.info.directBootAware = true;
10802                }
10803                for (PackageParser.Provider p : pkg.providers) {
10804                    p.info.encryptionAware = p.info.directBootAware = true;
10805                }
10806                for (PackageParser.Activity a : pkg.activities) {
10807                    a.info.encryptionAware = a.info.directBootAware = true;
10808                }
10809                for (PackageParser.Activity r : pkg.receivers) {
10810                    r.info.encryptionAware = r.info.directBootAware = true;
10811                }
10812            }
10813            if (compressedFileExists(pkg.codePath)) {
10814                pkg.isStub = true;
10815            }
10816        } else {
10817            // non system apps can't be flagged as core
10818            pkg.coreApp = false;
10819            // clear flags not applicable to regular apps
10820            pkg.applicationInfo.flags &=
10821                    ~ApplicationInfo.FLAG_PERSISTENT;
10822            pkg.applicationInfo.privateFlags &=
10823                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10824            pkg.applicationInfo.privateFlags &=
10825                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10826            // cap permission priorities
10827            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10828                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10829                    pkg.permissionGroups.get(i).info.priority = 0;
10830                }
10831            }
10832        }
10833        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10834            // clear protected broadcasts
10835            pkg.protectedBroadcasts = null;
10836            // ignore export request for single user receivers
10837            if (pkg.receivers != null) {
10838                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10839                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10840                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10841                        receiver.info.exported = false;
10842                    }
10843                }
10844            }
10845            // ignore export request for single user services
10846            if (pkg.services != null) {
10847                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10848                    final PackageParser.Service service = pkg.services.get(i);
10849                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10850                        service.info.exported = false;
10851                    }
10852                }
10853            }
10854            // ignore export request for single user providers
10855            if (pkg.providers != null) {
10856                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10857                    final PackageParser.Provider provider = pkg.providers.get(i);
10858                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10859                        provider.info.exported = false;
10860                    }
10861                }
10862            }
10863        }
10864
10865        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10866            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10867        }
10868
10869        if ((scanFlags & SCAN_AS_OEM) != 0) {
10870            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10871        }
10872
10873        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10874            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10875        }
10876
10877        if ((scanFlags & SCAN_AS_PRODUCT) != 0) {
10878            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT;
10879        }
10880
10881        // Check if the package is signed with the same key as the platform package.
10882        if (PLATFORM_PACKAGE_NAME.equals(pkg.packageName) ||
10883                (platformPkg != null && compareSignatures(
10884                        platformPkg.mSigningDetails.signatures,
10885                        pkg.mSigningDetails.signatures) == PackageManager.SIGNATURE_MATCH)) {
10886            pkg.applicationInfo.privateFlags |=
10887                ApplicationInfo.PRIVATE_FLAG_SIGNED_WITH_PLATFORM_KEY;
10888        }
10889
10890        if (!isSystemApp(pkg)) {
10891            // Only system apps can use these features.
10892            pkg.mOriginalPackages = null;
10893            pkg.mRealPackage = null;
10894            pkg.mAdoptPermissions = null;
10895        }
10896    }
10897
10898    private static @NonNull <T> T assertNotNull(@Nullable T object, String message)
10899            throws PackageManagerException {
10900        if (object == null) {
10901            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message);
10902        }
10903        return object;
10904    }
10905
10906    /**
10907     * Asserts the parsed package is valid according to the given policy. If the
10908     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10909     * <p>
10910     * Implementation detail: This method must NOT have any side effects. It would
10911     * ideally be static, but, it requires locks to read system state.
10912     *
10913     * @throws PackageManagerException If the package fails any of the validation checks
10914     */
10915    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10916            final @ScanFlags int scanFlags)
10917                    throws PackageManagerException {
10918        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10919            assertCodePolicy(pkg);
10920        }
10921
10922        if (pkg.applicationInfo.getCodePath() == null ||
10923                pkg.applicationInfo.getResourcePath() == null) {
10924            // Bail out. The resource and code paths haven't been set.
10925            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10926                    "Code and resource paths haven't been set correctly");
10927        }
10928
10929        // Make sure we're not adding any bogus keyset info
10930        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10931        ksms.assertScannedPackageValid(pkg);
10932
10933        synchronized (mPackages) {
10934            // The special "android" package can only be defined once
10935            if (pkg.packageName.equals("android")) {
10936                if (mAndroidApplication != null) {
10937                    Slog.w(TAG, "*************************************************");
10938                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10939                    Slog.w(TAG, " codePath=" + pkg.codePath);
10940                    Slog.w(TAG, "*************************************************");
10941                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10942                            "Core android package being redefined.  Skipping.");
10943                }
10944            }
10945
10946            // A package name must be unique; don't allow duplicates
10947            if (mPackages.containsKey(pkg.packageName)) {
10948                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10949                        "Application package " + pkg.packageName
10950                        + " already installed.  Skipping duplicate.");
10951            }
10952
10953            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10954                // Static libs have a synthetic package name containing the version
10955                // but we still want the base name to be unique.
10956                if (mPackages.containsKey(pkg.manifestPackageName)) {
10957                    throw new PackageManagerException(
10958                            "Duplicate static shared lib provider package");
10959                }
10960
10961                // Static shared libraries should have at least O target SDK
10962                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10963                    throw new PackageManagerException(
10964                            "Packages declaring static-shared libs must target O SDK or higher");
10965                }
10966
10967                // Package declaring static a shared lib cannot be instant apps
10968                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10969                    throw new PackageManagerException(
10970                            "Packages declaring static-shared libs cannot be instant apps");
10971                }
10972
10973                // Package declaring static a shared lib cannot be renamed since the package
10974                // name is synthetic and apps can't code around package manager internals.
10975                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10976                    throw new PackageManagerException(
10977                            "Packages declaring static-shared libs cannot be renamed");
10978                }
10979
10980                // Package declaring static a shared lib cannot declare child packages
10981                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10982                    throw new PackageManagerException(
10983                            "Packages declaring static-shared libs cannot have child packages");
10984                }
10985
10986                // Package declaring static a shared lib cannot declare dynamic libs
10987                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10988                    throw new PackageManagerException(
10989                            "Packages declaring static-shared libs cannot declare dynamic libs");
10990                }
10991
10992                // Package declaring static a shared lib cannot declare shared users
10993                if (pkg.mSharedUserId != null) {
10994                    throw new PackageManagerException(
10995                            "Packages declaring static-shared libs cannot declare shared users");
10996                }
10997
10998                // Static shared libs cannot declare activities
10999                if (!pkg.activities.isEmpty()) {
11000                    throw new PackageManagerException(
11001                            "Static shared libs cannot declare activities");
11002                }
11003
11004                // Static shared libs cannot declare services
11005                if (!pkg.services.isEmpty()) {
11006                    throw new PackageManagerException(
11007                            "Static shared libs cannot declare services");
11008                }
11009
11010                // Static shared libs cannot declare providers
11011                if (!pkg.providers.isEmpty()) {
11012                    throw new PackageManagerException(
11013                            "Static shared libs cannot declare content providers");
11014                }
11015
11016                // Static shared libs cannot declare receivers
11017                if (!pkg.receivers.isEmpty()) {
11018                    throw new PackageManagerException(
11019                            "Static shared libs cannot declare broadcast receivers");
11020                }
11021
11022                // Static shared libs cannot declare permission groups
11023                if (!pkg.permissionGroups.isEmpty()) {
11024                    throw new PackageManagerException(
11025                            "Static shared libs cannot declare permission groups");
11026                }
11027
11028                // Static shared libs cannot declare permissions
11029                if (!pkg.permissions.isEmpty()) {
11030                    throw new PackageManagerException(
11031                            "Static shared libs cannot declare permissions");
11032                }
11033
11034                // Static shared libs cannot declare protected broadcasts
11035                if (pkg.protectedBroadcasts != null) {
11036                    throw new PackageManagerException(
11037                            "Static shared libs cannot declare protected broadcasts");
11038                }
11039
11040                // Static shared libs cannot be overlay targets
11041                if (pkg.mOverlayTarget != null) {
11042                    throw new PackageManagerException(
11043                            "Static shared libs cannot be overlay targets");
11044                }
11045
11046                // The version codes must be ordered as lib versions
11047                long minVersionCode = Long.MIN_VALUE;
11048                long maxVersionCode = Long.MAX_VALUE;
11049
11050                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
11051                        pkg.staticSharedLibName);
11052                if (versionedLib != null) {
11053                    final int versionCount = versionedLib.size();
11054                    for (int i = 0; i < versionCount; i++) {
11055                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
11056                        final long libVersionCode = libInfo.getDeclaringPackage()
11057                                .getLongVersionCode();
11058                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
11059                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
11060                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
11061                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
11062                        } else {
11063                            minVersionCode = maxVersionCode = libVersionCode;
11064                            break;
11065                        }
11066                    }
11067                }
11068                if (pkg.getLongVersionCode() < minVersionCode
11069                        || pkg.getLongVersionCode() > maxVersionCode) {
11070                    throw new PackageManagerException("Static shared"
11071                            + " lib version codes must be ordered as lib versions");
11072                }
11073            }
11074
11075            // Only privileged apps and updated privileged apps can add child packages.
11076            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
11077                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
11078                    throw new PackageManagerException("Only privileged apps can add child "
11079                            + "packages. Ignoring package " + pkg.packageName);
11080                }
11081                final int childCount = pkg.childPackages.size();
11082                for (int i = 0; i < childCount; i++) {
11083                    PackageParser.Package childPkg = pkg.childPackages.get(i);
11084                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
11085                            childPkg.packageName)) {
11086                        throw new PackageManagerException("Can't override child of "
11087                                + "another disabled app. Ignoring package " + pkg.packageName);
11088                    }
11089                }
11090            }
11091
11092            // If we're only installing presumed-existing packages, require that the
11093            // scanned APK is both already known and at the path previously established
11094            // for it.  Previously unknown packages we pick up normally, but if we have an
11095            // a priori expectation about this package's install presence, enforce it.
11096            // With a singular exception for new system packages. When an OTA contains
11097            // a new system package, we allow the codepath to change from a system location
11098            // to the user-installed location. If we don't allow this change, any newer,
11099            // user-installed version of the application will be ignored.
11100            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11101                if (mExpectingBetter.containsKey(pkg.packageName)) {
11102                    logCriticalInfo(Log.WARN,
11103                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11104                } else {
11105                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11106                    if (known != null) {
11107                        if (DEBUG_PACKAGE_SCANNING) {
11108                            Log.d(TAG, "Examining " + pkg.codePath
11109                                    + " and requiring known paths " + known.codePathString
11110                                    + " & " + known.resourcePathString);
11111                        }
11112                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11113                                || !pkg.applicationInfo.getResourcePath().equals(
11114                                        known.resourcePathString)) {
11115                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11116                                    "Application package " + pkg.packageName
11117                                    + " found at " + pkg.applicationInfo.getCodePath()
11118                                    + " but expected at " + known.codePathString
11119                                    + "; ignoring.");
11120                        }
11121                    } else {
11122                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11123                                "Application package " + pkg.packageName
11124                                + " not found; ignoring.");
11125                    }
11126                }
11127            }
11128
11129            // Verify that this new package doesn't have any content providers
11130            // that conflict with existing packages.  Only do this if the
11131            // package isn't already installed, since we don't want to break
11132            // things that are installed.
11133            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11134                final int N = pkg.providers.size();
11135                int i;
11136                for (i=0; i<N; i++) {
11137                    PackageParser.Provider p = pkg.providers.get(i);
11138                    if (p.info.authority != null) {
11139                        String names[] = p.info.authority.split(";");
11140                        for (int j = 0; j < names.length; j++) {
11141                            if (mProvidersByAuthority.containsKey(names[j])) {
11142                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11143                                final String otherPackageName =
11144                                        ((other != null && other.getComponentName() != null) ?
11145                                                other.getComponentName().getPackageName() : "?");
11146                                throw new PackageManagerException(
11147                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11148                                        "Can't install because provider name " + names[j]
11149                                                + " (in package " + pkg.applicationInfo.packageName
11150                                                + ") is already used by " + otherPackageName);
11151                            }
11152                        }
11153                    }
11154                }
11155            }
11156
11157            // Verify that packages sharing a user with a privileged app are marked as privileged.
11158            if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
11159                SharedUserSetting sharedUserSetting = null;
11160                try {
11161                    sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
11162                } catch (PackageManagerException ignore) {}
11163                if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
11164                    // Exempt SharedUsers signed with the platform key.
11165                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
11166                    if ((platformPkgSetting.signatures.mSigningDetails
11167                            != PackageParser.SigningDetails.UNKNOWN)
11168                            && (compareSignatures(
11169                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11170                                    pkg.mSigningDetails.signatures)
11171                                            != PackageManager.SIGNATURE_MATCH)) {
11172                        throw new PackageManagerException("Apps that share a user with a " +
11173                                "privileged app must themselves be marked as privileged. " +
11174                                pkg.packageName + " shares privileged user " +
11175                                pkg.mSharedUserId + ".");
11176                    }
11177                }
11178            }
11179
11180            // Apply policies specific for runtime resource overlays (RROs).
11181            if (pkg.mOverlayTarget != null) {
11182                // System overlays have some restrictions on their use of the 'static' state.
11183                if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
11184                    // We are scanning a system overlay. This can be the first scan of the
11185                    // system/vendor/oem partition, or an update to the system overlay.
11186                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
11187                        // This must be an update to a system overlay.
11188                        final PackageSetting previousPkg = assertNotNull(
11189                                mSettings.getPackageLPr(pkg.packageName),
11190                                "previous package state not present");
11191
11192                        // previousPkg.pkg may be null: the package will be not be scanned if the
11193                        // package manager knows there is a newer version on /data.
11194                        // TODO[b/79435695]: Find a better way to keep track of the "static"
11195                        // property for RROs instead of having to parse packages on /system
11196                        PackageParser.Package ppkg = previousPkg.pkg;
11197                        if (ppkg == null) {
11198                            try {
11199                                final PackageParser pp = new PackageParser();
11200                                ppkg = pp.parsePackage(previousPkg.codePath,
11201                                        parseFlags | PackageParser.PARSE_IS_SYSTEM_DIR);
11202                            } catch (PackageParserException e) {
11203                                Slog.w(TAG, "failed to parse " + previousPkg.codePath, e);
11204                            }
11205                        }
11206
11207                        // Static overlays cannot be updated.
11208                        if (ppkg != null && ppkg.mOverlayIsStatic) {
11209                            throw new PackageManagerException("Overlay " + pkg.packageName +
11210                                    " is static and cannot be upgraded.");
11211                        // Non-static overlays cannot be converted to static overlays.
11212                        } else if (pkg.mOverlayIsStatic) {
11213                            throw new PackageManagerException("Overlay " + pkg.packageName +
11214                                    " cannot be upgraded into a static overlay.");
11215                        }
11216                    }
11217                } else {
11218                    // The overlay is a non-system overlay. Non-system overlays cannot be static.
11219                    if (pkg.mOverlayIsStatic) {
11220                        throw new PackageManagerException("Overlay " + pkg.packageName +
11221                                " is static but not pre-installed.");
11222                    }
11223
11224                    // The only case where we allow installation of a non-system overlay is when
11225                    // its signature is signed with the platform certificate.
11226                    PackageSetting platformPkgSetting = mSettings.getPackageLPr("android");
11227                    if ((platformPkgSetting.signatures.mSigningDetails
11228                            != PackageParser.SigningDetails.UNKNOWN)
11229                            && (compareSignatures(
11230                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11231                                    pkg.mSigningDetails.signatures)
11232                                            != PackageManager.SIGNATURE_MATCH)) {
11233                        throw new PackageManagerException("Overlay " + pkg.packageName +
11234                                " must be signed with the platform certificate.");
11235                    }
11236                }
11237            }
11238        }
11239    }
11240
11241    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
11242            int type, String declaringPackageName, long declaringVersionCode) {
11243        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11244        if (versionedLib == null) {
11245            versionedLib = new LongSparseArray<>();
11246            mSharedLibraries.put(name, versionedLib);
11247            if (type == SharedLibraryInfo.TYPE_STATIC) {
11248                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11249            }
11250        } else if (versionedLib.indexOfKey(version) >= 0) {
11251            return false;
11252        }
11253        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11254                version, type, declaringPackageName, declaringVersionCode);
11255        versionedLib.put(version, libEntry);
11256        return true;
11257    }
11258
11259    private boolean removeSharedLibraryLPw(String name, long version) {
11260        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11261        if (versionedLib == null) {
11262            return false;
11263        }
11264        final int libIdx = versionedLib.indexOfKey(version);
11265        if (libIdx < 0) {
11266            return false;
11267        }
11268        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11269        versionedLib.remove(version);
11270        if (versionedLib.size() <= 0) {
11271            mSharedLibraries.remove(name);
11272            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11273                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11274                        .getPackageName());
11275            }
11276        }
11277        return true;
11278    }
11279
11280    /**
11281     * Adds a scanned package to the system. When this method is finished, the package will
11282     * be available for query, resolution, etc...
11283     */
11284    private void commitPackageSettings(PackageParser.Package pkg,
11285            @Nullable PackageParser.Package oldPkg, PackageSetting pkgSetting, UserHandle user,
11286            final @ScanFlags int scanFlags, boolean chatty) {
11287        final String pkgName = pkg.packageName;
11288        if (mCustomResolverComponentName != null &&
11289                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11290            setUpCustomResolverActivity(pkg);
11291        }
11292
11293        if (pkg.packageName.equals("android")) {
11294            synchronized (mPackages) {
11295                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11296                    // Set up information for our fall-back user intent resolution activity.
11297                    mPlatformPackage = pkg;
11298                    pkg.mVersionCode = mSdkVersion;
11299                    pkg.mVersionCodeMajor = 0;
11300                    mAndroidApplication = pkg.applicationInfo;
11301                    if (!mResolverReplaced) {
11302                        mResolveActivity.applicationInfo = mAndroidApplication;
11303                        mResolveActivity.name = ResolverActivity.class.getName();
11304                        mResolveActivity.packageName = mAndroidApplication.packageName;
11305                        mResolveActivity.processName = "system:ui";
11306                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11307                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11308                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11309                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11310                        mResolveActivity.exported = true;
11311                        mResolveActivity.enabled = true;
11312                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11313                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11314                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11315                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11316                                | ActivityInfo.CONFIG_ORIENTATION
11317                                | ActivityInfo.CONFIG_KEYBOARD
11318                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11319                        mResolveInfo.activityInfo = mResolveActivity;
11320                        mResolveInfo.priority = 0;
11321                        mResolveInfo.preferredOrder = 0;
11322                        mResolveInfo.match = 0;
11323                        mResolveComponentName = new ComponentName(
11324                                mAndroidApplication.packageName, mResolveActivity.name);
11325                    }
11326                }
11327            }
11328        }
11329
11330        ArrayList<PackageParser.Package> clientLibPkgs = null;
11331        // writer
11332        synchronized (mPackages) {
11333            boolean hasStaticSharedLibs = false;
11334
11335            // Any app can add new static shared libraries
11336            if (pkg.staticSharedLibName != null) {
11337                // Static shared libs don't allow renaming as they have synthetic package
11338                // names to allow install of multiple versions, so use name from manifest.
11339                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11340                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11341                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
11342                    hasStaticSharedLibs = true;
11343                } else {
11344                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11345                                + pkg.staticSharedLibName + " already exists; skipping");
11346                }
11347                // Static shared libs cannot be updated once installed since they
11348                // use synthetic package name which includes the version code, so
11349                // not need to update other packages's shared lib dependencies.
11350            }
11351
11352            if (!hasStaticSharedLibs
11353                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11354                // Only system apps can add new dynamic shared libraries.
11355                if (pkg.libraryNames != null) {
11356                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11357                        String name = pkg.libraryNames.get(i);
11358                        boolean allowed = false;
11359                        if (pkg.isUpdatedSystemApp()) {
11360                            // New library entries can only be added through the
11361                            // system image.  This is important to get rid of a lot
11362                            // of nasty edge cases: for example if we allowed a non-
11363                            // system update of the app to add a library, then uninstalling
11364                            // the update would make the library go away, and assumptions
11365                            // we made such as through app install filtering would now
11366                            // have allowed apps on the device which aren't compatible
11367                            // with it.  Better to just have the restriction here, be
11368                            // conservative, and create many fewer cases that can negatively
11369                            // impact the user experience.
11370                            final PackageSetting sysPs = mSettings
11371                                    .getDisabledSystemPkgLPr(pkg.packageName);
11372                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11373                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11374                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11375                                        allowed = true;
11376                                        break;
11377                                    }
11378                                }
11379                            }
11380                        } else {
11381                            allowed = true;
11382                        }
11383                        if (allowed) {
11384                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11385                                    SharedLibraryInfo.VERSION_UNDEFINED,
11386                                    SharedLibraryInfo.TYPE_DYNAMIC,
11387                                    pkg.packageName, pkg.getLongVersionCode())) {
11388                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11389                                        + name + " already exists; skipping");
11390                            }
11391                        } else {
11392                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11393                                    + name + " that is not declared on system image; skipping");
11394                        }
11395                    }
11396
11397                    if ((scanFlags & SCAN_BOOTING) == 0) {
11398                        // If we are not booting, we need to update any applications
11399                        // that are clients of our shared library.  If we are booting,
11400                        // this will all be done once the scan is complete.
11401                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11402                    }
11403                }
11404            }
11405        }
11406
11407        if ((scanFlags & SCAN_BOOTING) != 0) {
11408            // No apps can run during boot scan, so they don't need to be frozen
11409        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11410            // Caller asked to not kill app, so it's probably not frozen
11411        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11412            // Caller asked us to ignore frozen check for some reason; they
11413            // probably didn't know the package name
11414        } else {
11415            // We're doing major surgery on this package, so it better be frozen
11416            // right now to keep it from launching
11417            checkPackageFrozen(pkgName);
11418        }
11419
11420        // Also need to kill any apps that are dependent on the library.
11421        if (clientLibPkgs != null) {
11422            for (int i=0; i<clientLibPkgs.size(); i++) {
11423                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11424                killApplication(clientPkg.applicationInfo.packageName,
11425                        clientPkg.applicationInfo.uid, "update lib");
11426            }
11427        }
11428
11429        // writer
11430        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11431
11432        synchronized (mPackages) {
11433            // We don't expect installation to fail beyond this point
11434
11435            // Add the new setting to mSettings
11436            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11437            // Add the new setting to mPackages
11438            mPackages.put(pkg.applicationInfo.packageName, pkg);
11439            // Make sure we don't accidentally delete its data.
11440            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11441            while (iter.hasNext()) {
11442                PackageCleanItem item = iter.next();
11443                if (pkgName.equals(item.packageName)) {
11444                    iter.remove();
11445                }
11446            }
11447
11448            // Add the package's KeySets to the global KeySetManagerService
11449            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11450            ksms.addScannedPackageLPw(pkg);
11451
11452            int N = pkg.providers.size();
11453            StringBuilder r = null;
11454            int i;
11455            for (i=0; i<N; i++) {
11456                PackageParser.Provider p = pkg.providers.get(i);
11457                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11458                        p.info.processName);
11459                mProviders.addProvider(p);
11460                p.syncable = p.info.isSyncable;
11461                if (p.info.authority != null) {
11462                    String names[] = p.info.authority.split(";");
11463                    p.info.authority = null;
11464                    for (int j = 0; j < names.length; j++) {
11465                        if (j == 1 && p.syncable) {
11466                            // We only want the first authority for a provider to possibly be
11467                            // syncable, so if we already added this provider using a different
11468                            // authority clear the syncable flag. We copy the provider before
11469                            // changing it because the mProviders object contains a reference
11470                            // to a provider that we don't want to change.
11471                            // Only do this for the second authority since the resulting provider
11472                            // object can be the same for all future authorities for this provider.
11473                            p = new PackageParser.Provider(p);
11474                            p.syncable = false;
11475                        }
11476                        if (!mProvidersByAuthority.containsKey(names[j])) {
11477                            mProvidersByAuthority.put(names[j], p);
11478                            if (p.info.authority == null) {
11479                                p.info.authority = names[j];
11480                            } else {
11481                                p.info.authority = p.info.authority + ";" + names[j];
11482                            }
11483                            if (DEBUG_PACKAGE_SCANNING) {
11484                                if (chatty)
11485                                    Log.d(TAG, "Registered content provider: " + names[j]
11486                                            + ", className = " + p.info.name + ", isSyncable = "
11487                                            + p.info.isSyncable);
11488                            }
11489                        } else {
11490                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11491                            Slog.w(TAG, "Skipping provider name " + names[j] +
11492                                    " (in package " + pkg.applicationInfo.packageName +
11493                                    "): name already used by "
11494                                    + ((other != null && other.getComponentName() != null)
11495                                            ? other.getComponentName().getPackageName() : "?"));
11496                        }
11497                    }
11498                }
11499                if (chatty) {
11500                    if (r == null) {
11501                        r = new StringBuilder(256);
11502                    } else {
11503                        r.append(' ');
11504                    }
11505                    r.append(p.info.name);
11506                }
11507            }
11508            if (r != null) {
11509                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11510            }
11511
11512            N = pkg.services.size();
11513            r = null;
11514            for (i=0; i<N; i++) {
11515                PackageParser.Service s = pkg.services.get(i);
11516                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11517                        s.info.processName);
11518                mServices.addService(s);
11519                if (chatty) {
11520                    if (r == null) {
11521                        r = new StringBuilder(256);
11522                    } else {
11523                        r.append(' ');
11524                    }
11525                    r.append(s.info.name);
11526                }
11527            }
11528            if (r != null) {
11529                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11530            }
11531
11532            N = pkg.receivers.size();
11533            r = null;
11534            for (i=0; i<N; i++) {
11535                PackageParser.Activity a = pkg.receivers.get(i);
11536                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11537                        a.info.processName);
11538                mReceivers.addActivity(a, "receiver");
11539                if (chatty) {
11540                    if (r == null) {
11541                        r = new StringBuilder(256);
11542                    } else {
11543                        r.append(' ');
11544                    }
11545                    r.append(a.info.name);
11546                }
11547            }
11548            if (r != null) {
11549                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11550            }
11551
11552            N = pkg.activities.size();
11553            r = null;
11554            for (i=0; i<N; i++) {
11555                PackageParser.Activity a = pkg.activities.get(i);
11556                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11557                        a.info.processName);
11558                mActivities.addActivity(a, "activity");
11559                if (chatty) {
11560                    if (r == null) {
11561                        r = new StringBuilder(256);
11562                    } else {
11563                        r.append(' ');
11564                    }
11565                    r.append(a.info.name);
11566                }
11567            }
11568            if (r != null) {
11569                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11570            }
11571
11572            // Don't allow ephemeral applications to define new permissions groups.
11573            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11574                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11575                        + " ignored: instant apps cannot define new permission groups.");
11576            } else {
11577                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11578            }
11579
11580            // Don't allow ephemeral applications to define new permissions.
11581            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11582                Slog.w(TAG, "Permissions from package " + pkg.packageName
11583                        + " ignored: instant apps cannot define new permissions.");
11584            } else {
11585                mPermissionManager.addAllPermissions(pkg, chatty);
11586            }
11587
11588            N = pkg.instrumentation.size();
11589            r = null;
11590            for (i=0; i<N; i++) {
11591                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11592                a.info.packageName = pkg.applicationInfo.packageName;
11593                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11594                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11595                a.info.splitNames = pkg.splitNames;
11596                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11597                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11598                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11599                a.info.dataDir = pkg.applicationInfo.dataDir;
11600                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11601                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11602                a.info.primaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11603                a.info.secondaryCpuAbi = pkg.applicationInfo.secondaryCpuAbi;
11604                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11605                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11606                mInstrumentation.put(a.getComponentName(), a);
11607                if (chatty) {
11608                    if (r == null) {
11609                        r = new StringBuilder(256);
11610                    } else {
11611                        r.append(' ');
11612                    }
11613                    r.append(a.info.name);
11614                }
11615            }
11616            if (r != null) {
11617                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11618            }
11619
11620            if (pkg.protectedBroadcasts != null) {
11621                N = pkg.protectedBroadcasts.size();
11622                synchronized (mProtectedBroadcasts) {
11623                    for (i = 0; i < N; i++) {
11624                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11625                    }
11626                }
11627            }
11628
11629            if (oldPkg != null) {
11630                // We need to call revokeRuntimePermissionsIfGroupChanged async as permission
11631                // revoke callbacks from this method might need to kill apps which need the
11632                // mPackages lock on a different thread. This would dead lock.
11633                //
11634                // Hence create a copy of all package names and pass it into
11635                // revokeRuntimePermissionsIfGroupChanged. Only for those permissions might get
11636                // revoked. If a new package is added before the async code runs the permission
11637                // won't be granted yet, hence new packages are no problem.
11638                final ArrayList<String> allPackageNames = new ArrayList<>(mPackages.keySet());
11639
11640                AsyncTask.execute(() ->
11641                        mPermissionManager.revokeRuntimePermissionsIfGroupChanged(pkg, oldPkg,
11642                                allPackageNames, mPermissionCallback));
11643            }
11644        }
11645
11646        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11647    }
11648
11649    /**
11650     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11651     * is derived purely on the basis of the contents of {@code scanFile} and
11652     * {@code cpuAbiOverride}.
11653     *
11654     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11655     */
11656    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11657            boolean extractLibs)
11658                    throws PackageManagerException {
11659        // Give ourselves some initial paths; we'll come back for another
11660        // pass once we've determined ABI below.
11661        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11662
11663        // We would never need to extract libs for forward-locked and external packages,
11664        // since the container service will do it for us. We shouldn't attempt to
11665        // extract libs from system app when it was not updated.
11666        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11667                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11668            extractLibs = false;
11669        }
11670
11671        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11672        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11673
11674        NativeLibraryHelper.Handle handle = null;
11675        try {
11676            handle = NativeLibraryHelper.Handle.create(pkg);
11677            // TODO(multiArch): This can be null for apps that didn't go through the
11678            // usual installation process. We can calculate it again, like we
11679            // do during install time.
11680            //
11681            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11682            // unnecessary.
11683            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11684
11685            // Null out the abis so that they can be recalculated.
11686            pkg.applicationInfo.primaryCpuAbi = null;
11687            pkg.applicationInfo.secondaryCpuAbi = null;
11688            if (isMultiArch(pkg.applicationInfo)) {
11689                // Warn if we've set an abiOverride for multi-lib packages..
11690                // By definition, we need to copy both 32 and 64 bit libraries for
11691                // such packages.
11692                if (pkg.cpuAbiOverride != null
11693                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11694                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11695                }
11696
11697                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11698                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11699                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11700                    if (extractLibs) {
11701                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11702                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11703                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11704                                useIsaSpecificSubdirs);
11705                    } else {
11706                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11707                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11708                    }
11709                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11710                }
11711
11712                // Shared library native code should be in the APK zip aligned
11713                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11714                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11715                            "Shared library native lib extraction not supported");
11716                }
11717
11718                maybeThrowExceptionForMultiArchCopy(
11719                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11720
11721                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11722                    if (extractLibs) {
11723                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11724                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11725                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11726                                useIsaSpecificSubdirs);
11727                    } else {
11728                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11729                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11730                    }
11731                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11732                }
11733
11734                maybeThrowExceptionForMultiArchCopy(
11735                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11736
11737                if (abi64 >= 0) {
11738                    // Shared library native libs should be in the APK zip aligned
11739                    if (extractLibs && pkg.isLibrary()) {
11740                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11741                                "Shared library native lib extraction not supported");
11742                    }
11743                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11744                }
11745
11746                if (abi32 >= 0) {
11747                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11748                    if (abi64 >= 0) {
11749                        if (pkg.use32bitAbi) {
11750                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11751                            pkg.applicationInfo.primaryCpuAbi = abi;
11752                        } else {
11753                            pkg.applicationInfo.secondaryCpuAbi = abi;
11754                        }
11755                    } else {
11756                        pkg.applicationInfo.primaryCpuAbi = abi;
11757                    }
11758                }
11759            } else {
11760                String[] abiList = (cpuAbiOverride != null) ?
11761                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11762
11763                // Enable gross and lame hacks for apps that are built with old
11764                // SDK tools. We must scan their APKs for renderscript bitcode and
11765                // not launch them if it's present. Don't bother checking on devices
11766                // that don't have 64 bit support.
11767                boolean needsRenderScriptOverride = false;
11768                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11769                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11770                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11771                    needsRenderScriptOverride = true;
11772                }
11773
11774                final int copyRet;
11775                if (extractLibs) {
11776                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11777                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11778                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11779                } else {
11780                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11781                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11782                }
11783                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11784
11785                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11786                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11787                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11788                }
11789
11790                if (copyRet >= 0) {
11791                    // Shared libraries that have native libs must be multi-architecture
11792                    if (pkg.isLibrary()) {
11793                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11794                                "Shared library with native libs must be multiarch");
11795                    }
11796                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11797                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11798                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11799                } else if (needsRenderScriptOverride) {
11800                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11801                }
11802            }
11803        } catch (IOException ioe) {
11804            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11805        } finally {
11806            IoUtils.closeQuietly(handle);
11807        }
11808
11809        // Now that we've calculated the ABIs and determined if it's an internal app,
11810        // we will go ahead and populate the nativeLibraryPath.
11811        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11812    }
11813
11814    /**
11815     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11816     * i.e, so that all packages can be run inside a single process if required.
11817     *
11818     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11819     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11820     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11821     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11822     * updating a package that belongs to a shared user.
11823     *
11824     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11825     * adds unnecessary complexity.
11826     */
11827    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11828            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11829        List<String> changedAbiCodePath = null;
11830        String requiredInstructionSet = null;
11831        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11832            requiredInstructionSet = VMRuntime.getInstructionSet(
11833                     scannedPackage.applicationInfo.primaryCpuAbi);
11834        }
11835
11836        PackageSetting requirer = null;
11837        for (PackageSetting ps : packagesForUser) {
11838            // If packagesForUser contains scannedPackage, we skip it. This will happen
11839            // when scannedPackage is an update of an existing package. Without this check,
11840            // we will never be able to change the ABI of any package belonging to a shared
11841            // user, even if it's compatible with other packages.
11842            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11843                if (ps.primaryCpuAbiString == null) {
11844                    continue;
11845                }
11846
11847                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11848                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11849                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11850                    // this but there's not much we can do.
11851                    String errorMessage = "Instruction set mismatch, "
11852                            + ((requirer == null) ? "[caller]" : requirer)
11853                            + " requires " + requiredInstructionSet + " whereas " + ps
11854                            + " requires " + instructionSet;
11855                    Slog.w(TAG, errorMessage);
11856                }
11857
11858                if (requiredInstructionSet == null) {
11859                    requiredInstructionSet = instructionSet;
11860                    requirer = ps;
11861                }
11862            }
11863        }
11864
11865        if (requiredInstructionSet != null) {
11866            String adjustedAbi;
11867            if (requirer != null) {
11868                // requirer != null implies that either scannedPackage was null or that scannedPackage
11869                // did not require an ABI, in which case we have to adjust scannedPackage to match
11870                // the ABI of the set (which is the same as requirer's ABI)
11871                adjustedAbi = requirer.primaryCpuAbiString;
11872                if (scannedPackage != null) {
11873                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11874                }
11875            } else {
11876                // requirer == null implies that we're updating all ABIs in the set to
11877                // match scannedPackage.
11878                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11879            }
11880
11881            for (PackageSetting ps : packagesForUser) {
11882                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11883                    if (ps.primaryCpuAbiString != null) {
11884                        continue;
11885                    }
11886
11887                    ps.primaryCpuAbiString = adjustedAbi;
11888                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11889                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11890                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11891                        if (DEBUG_ABI_SELECTION) {
11892                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11893                                    + " (requirer="
11894                                    + (requirer != null ? requirer.pkg : "null")
11895                                    + ", scannedPackage="
11896                                    + (scannedPackage != null ? scannedPackage : "null")
11897                                    + ")");
11898                        }
11899                        if (changedAbiCodePath == null) {
11900                            changedAbiCodePath = new ArrayList<>();
11901                        }
11902                        changedAbiCodePath.add(ps.codePathString);
11903                    }
11904                }
11905            }
11906        }
11907        return changedAbiCodePath;
11908    }
11909
11910    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11911        synchronized (mPackages) {
11912            mResolverReplaced = true;
11913            // Set up information for custom user intent resolution activity.
11914            mResolveActivity.applicationInfo = pkg.applicationInfo;
11915            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11916            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11917            mResolveActivity.processName = pkg.applicationInfo.packageName;
11918            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11919            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11920                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11921            mResolveActivity.theme = 0;
11922            mResolveActivity.exported = true;
11923            mResolveActivity.enabled = true;
11924            mResolveInfo.activityInfo = mResolveActivity;
11925            mResolveInfo.priority = 0;
11926            mResolveInfo.preferredOrder = 0;
11927            mResolveInfo.match = 0;
11928            mResolveComponentName = mCustomResolverComponentName;
11929            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11930                    mResolveComponentName);
11931        }
11932    }
11933
11934    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11935        if (installerActivity == null) {
11936            if (DEBUG_INSTANT) {
11937                Slog.d(TAG, "Clear ephemeral installer activity");
11938            }
11939            mInstantAppInstallerActivity = null;
11940            return;
11941        }
11942
11943        if (DEBUG_INSTANT) {
11944            Slog.d(TAG, "Set ephemeral installer activity: "
11945                    + installerActivity.getComponentName());
11946        }
11947        // Set up information for ephemeral installer activity
11948        mInstantAppInstallerActivity = installerActivity;
11949        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11950                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11951        mInstantAppInstallerActivity.exported = true;
11952        mInstantAppInstallerActivity.enabled = true;
11953        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11954        mInstantAppInstallerInfo.priority = 1;
11955        mInstantAppInstallerInfo.preferredOrder = 1;
11956        mInstantAppInstallerInfo.isDefault = true;
11957        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11958                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11959    }
11960
11961    private static String calculateBundledApkRoot(final String codePathString) {
11962        final File codePath = new File(codePathString);
11963        final File codeRoot;
11964        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11965            codeRoot = Environment.getRootDirectory();
11966        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11967            codeRoot = Environment.getOemDirectory();
11968        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11969            codeRoot = Environment.getVendorDirectory();
11970        } else if (FileUtils.contains(Environment.getOdmDirectory(), codePath)) {
11971            codeRoot = Environment.getOdmDirectory();
11972        } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) {
11973            codeRoot = Environment.getProductDirectory();
11974        } else {
11975            // Unrecognized code path; take its top real segment as the apk root:
11976            // e.g. /something/app/blah.apk => /something
11977            try {
11978                File f = codePath.getCanonicalFile();
11979                File parent = f.getParentFile();    // non-null because codePath is a file
11980                File tmp;
11981                while ((tmp = parent.getParentFile()) != null) {
11982                    f = parent;
11983                    parent = tmp;
11984                }
11985                codeRoot = f;
11986                Slog.w(TAG, "Unrecognized code path "
11987                        + codePath + " - using " + codeRoot);
11988            } catch (IOException e) {
11989                // Can't canonicalize the code path -- shenanigans?
11990                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11991                return Environment.getRootDirectory().getPath();
11992            }
11993        }
11994        return codeRoot.getPath();
11995    }
11996
11997    /**
11998     * Derive and set the location of native libraries for the given package,
11999     * which varies depending on where and how the package was installed.
12000     */
12001    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
12002        final ApplicationInfo info = pkg.applicationInfo;
12003        final String codePath = pkg.codePath;
12004        final File codeFile = new File(codePath);
12005        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
12006        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
12007
12008        info.nativeLibraryRootDir = null;
12009        info.nativeLibraryRootRequiresIsa = false;
12010        info.nativeLibraryDir = null;
12011        info.secondaryNativeLibraryDir = null;
12012
12013        if (isApkFile(codeFile)) {
12014            // Monolithic install
12015            if (bundledApp) {
12016                // If "/system/lib64/apkname" exists, assume that is the per-package
12017                // native library directory to use; otherwise use "/system/lib/apkname".
12018                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
12019                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
12020                        getPrimaryInstructionSet(info));
12021
12022                // This is a bundled system app so choose the path based on the ABI.
12023                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
12024                // is just the default path.
12025                final String apkName = deriveCodePathName(codePath);
12026                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
12027                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
12028                        apkName).getAbsolutePath();
12029
12030                if (info.secondaryCpuAbi != null) {
12031                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
12032                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
12033                            secondaryLibDir, apkName).getAbsolutePath();
12034                }
12035            } else if (asecApp) {
12036                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
12037                        .getAbsolutePath();
12038            } else {
12039                final String apkName = deriveCodePathName(codePath);
12040                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
12041                        .getAbsolutePath();
12042            }
12043
12044            info.nativeLibraryRootRequiresIsa = false;
12045            info.nativeLibraryDir = info.nativeLibraryRootDir;
12046        } else {
12047            // Cluster install
12048            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
12049            info.nativeLibraryRootRequiresIsa = true;
12050
12051            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
12052                    getPrimaryInstructionSet(info)).getAbsolutePath();
12053
12054            if (info.secondaryCpuAbi != null) {
12055                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
12056                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
12057            }
12058        }
12059    }
12060
12061    /**
12062     * Calculate the abis and roots for a bundled app. These can uniquely
12063     * be determined from the contents of the system partition, i.e whether
12064     * it contains 64 or 32 bit shared libraries etc. We do not validate any
12065     * of this information, and instead assume that the system was built
12066     * sensibly.
12067     */
12068    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
12069                                           PackageSetting pkgSetting) {
12070        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
12071
12072        // If "/system/lib64/apkname" exists, assume that is the per-package
12073        // native library directory to use; otherwise use "/system/lib/apkname".
12074        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
12075        setBundledAppAbi(pkg, apkRoot, apkName);
12076        // pkgSetting might be null during rescan following uninstall of updates
12077        // to a bundled app, so accommodate that possibility.  The settings in
12078        // that case will be established later from the parsed package.
12079        //
12080        // If the settings aren't null, sync them up with what we've just derived.
12081        // note that apkRoot isn't stored in the package settings.
12082        if (pkgSetting != null) {
12083            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
12084            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
12085        }
12086    }
12087
12088    /**
12089     * Deduces the ABI of a bundled app and sets the relevant fields on the
12090     * parsed pkg object.
12091     *
12092     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12093     *        under which system libraries are installed.
12094     * @param apkName the name of the installed package.
12095     */
12096    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12097        final File codeFile = new File(pkg.codePath);
12098
12099        final boolean has64BitLibs;
12100        final boolean has32BitLibs;
12101        if (isApkFile(codeFile)) {
12102            // Monolithic install
12103            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12104            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12105        } else {
12106            // Cluster install
12107            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12108            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12109                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12110                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12111                has64BitLibs = (new File(rootDir, isa)).exists();
12112            } else {
12113                has64BitLibs = false;
12114            }
12115            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12116                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12117                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12118                has32BitLibs = (new File(rootDir, isa)).exists();
12119            } else {
12120                has32BitLibs = false;
12121            }
12122        }
12123
12124        if (has64BitLibs && !has32BitLibs) {
12125            // The package has 64 bit libs, but not 32 bit libs. Its primary
12126            // ABI should be 64 bit. We can safely assume here that the bundled
12127            // native libraries correspond to the most preferred ABI in the list.
12128
12129            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12130            pkg.applicationInfo.secondaryCpuAbi = null;
12131        } else if (has32BitLibs && !has64BitLibs) {
12132            // The package has 32 bit libs but not 64 bit libs. Its primary
12133            // ABI should be 32 bit.
12134
12135            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12136            pkg.applicationInfo.secondaryCpuAbi = null;
12137        } else if (has32BitLibs && has64BitLibs) {
12138            // The application has both 64 and 32 bit bundled libraries. We check
12139            // here that the app declares multiArch support, and warn if it doesn't.
12140            //
12141            // We will be lenient here and record both ABIs. The primary will be the
12142            // ABI that's higher on the list, i.e, a device that's configured to prefer
12143            // 64 bit apps will see a 64 bit primary ABI,
12144
12145            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12146                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12147            }
12148
12149            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12150                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12151                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12152            } else {
12153                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12154                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12155            }
12156        } else {
12157            pkg.applicationInfo.primaryCpuAbi = null;
12158            pkg.applicationInfo.secondaryCpuAbi = null;
12159        }
12160    }
12161
12162    private void killApplication(String pkgName, int appId, String reason) {
12163        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12164    }
12165
12166    private void killApplication(String pkgName, int appId, int userId, String reason) {
12167        // Request the ActivityManager to kill the process(only for existing packages)
12168        // so that we do not end up in a confused state while the user is still using the older
12169        // version of the application while the new one gets installed.
12170        final long token = Binder.clearCallingIdentity();
12171        try {
12172            IActivityManager am = ActivityManager.getService();
12173            if (am != null) {
12174                try {
12175                    am.killApplication(pkgName, appId, userId, reason);
12176                } catch (RemoteException e) {
12177                }
12178            }
12179        } finally {
12180            Binder.restoreCallingIdentity(token);
12181        }
12182    }
12183
12184    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12185        // Remove the parent package setting
12186        PackageSetting ps = (PackageSetting) pkg.mExtras;
12187        if (ps != null) {
12188            removePackageLI(ps, chatty);
12189        }
12190        // Remove the child package setting
12191        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12192        for (int i = 0; i < childCount; i++) {
12193            PackageParser.Package childPkg = pkg.childPackages.get(i);
12194            ps = (PackageSetting) childPkg.mExtras;
12195            if (ps != null) {
12196                removePackageLI(ps, chatty);
12197            }
12198        }
12199    }
12200
12201    void removePackageLI(PackageSetting ps, boolean chatty) {
12202        if (DEBUG_INSTALL) {
12203            if (chatty)
12204                Log.d(TAG, "Removing package " + ps.name);
12205        }
12206
12207        // writer
12208        synchronized (mPackages) {
12209            mPackages.remove(ps.name);
12210            final PackageParser.Package pkg = ps.pkg;
12211            if (pkg != null) {
12212                cleanPackageDataStructuresLILPw(pkg, chatty);
12213            }
12214        }
12215    }
12216
12217    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12218        if (DEBUG_INSTALL) {
12219            if (chatty)
12220                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12221        }
12222
12223        // writer
12224        synchronized (mPackages) {
12225            // Remove the parent package
12226            mPackages.remove(pkg.applicationInfo.packageName);
12227            cleanPackageDataStructuresLILPw(pkg, chatty);
12228
12229            // Remove the child packages
12230            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12231            for (int i = 0; i < childCount; i++) {
12232                PackageParser.Package childPkg = pkg.childPackages.get(i);
12233                mPackages.remove(childPkg.applicationInfo.packageName);
12234                cleanPackageDataStructuresLILPw(childPkg, chatty);
12235            }
12236        }
12237    }
12238
12239    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12240        int N = pkg.providers.size();
12241        StringBuilder r = null;
12242        int i;
12243        for (i=0; i<N; i++) {
12244            PackageParser.Provider p = pkg.providers.get(i);
12245            mProviders.removeProvider(p);
12246            if (p.info.authority == null) {
12247
12248                /* There was another ContentProvider with this authority when
12249                 * this app was installed so this authority is null,
12250                 * Ignore it as we don't have to unregister the provider.
12251                 */
12252                continue;
12253            }
12254            String names[] = p.info.authority.split(";");
12255            for (int j = 0; j < names.length; j++) {
12256                if (mProvidersByAuthority.get(names[j]) == p) {
12257                    mProvidersByAuthority.remove(names[j]);
12258                    if (DEBUG_REMOVE) {
12259                        if (chatty)
12260                            Log.d(TAG, "Unregistered content provider: " + names[j]
12261                                    + ", className = " + p.info.name + ", isSyncable = "
12262                                    + p.info.isSyncable);
12263                    }
12264                }
12265            }
12266            if (DEBUG_REMOVE && chatty) {
12267                if (r == null) {
12268                    r = new StringBuilder(256);
12269                } else {
12270                    r.append(' ');
12271                }
12272                r.append(p.info.name);
12273            }
12274        }
12275        if (r != null) {
12276            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12277        }
12278
12279        N = pkg.services.size();
12280        r = null;
12281        for (i=0; i<N; i++) {
12282            PackageParser.Service s = pkg.services.get(i);
12283            mServices.removeService(s);
12284            if (chatty) {
12285                if (r == null) {
12286                    r = new StringBuilder(256);
12287                } else {
12288                    r.append(' ');
12289                }
12290                r.append(s.info.name);
12291            }
12292        }
12293        if (r != null) {
12294            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12295        }
12296
12297        N = pkg.receivers.size();
12298        r = null;
12299        for (i=0; i<N; i++) {
12300            PackageParser.Activity a = pkg.receivers.get(i);
12301            mReceivers.removeActivity(a, "receiver");
12302            if (DEBUG_REMOVE && chatty) {
12303                if (r == null) {
12304                    r = new StringBuilder(256);
12305                } else {
12306                    r.append(' ');
12307                }
12308                r.append(a.info.name);
12309            }
12310        }
12311        if (r != null) {
12312            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12313        }
12314
12315        N = pkg.activities.size();
12316        r = null;
12317        for (i=0; i<N; i++) {
12318            PackageParser.Activity a = pkg.activities.get(i);
12319            mActivities.removeActivity(a, "activity");
12320            if (DEBUG_REMOVE && chatty) {
12321                if (r == null) {
12322                    r = new StringBuilder(256);
12323                } else {
12324                    r.append(' ');
12325                }
12326                r.append(a.info.name);
12327            }
12328        }
12329        if (r != null) {
12330            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12331        }
12332
12333        mPermissionManager.removeAllPermissions(pkg, chatty);
12334
12335        N = pkg.instrumentation.size();
12336        r = null;
12337        for (i=0; i<N; i++) {
12338            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12339            mInstrumentation.remove(a.getComponentName());
12340            if (DEBUG_REMOVE && chatty) {
12341                if (r == null) {
12342                    r = new StringBuilder(256);
12343                } else {
12344                    r.append(' ');
12345                }
12346                r.append(a.info.name);
12347            }
12348        }
12349        if (r != null) {
12350            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12351        }
12352
12353        r = null;
12354        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12355            // Only system apps can hold shared libraries.
12356            if (pkg.libraryNames != null) {
12357                for (i = 0; i < pkg.libraryNames.size(); i++) {
12358                    String name = pkg.libraryNames.get(i);
12359                    if (removeSharedLibraryLPw(name, 0)) {
12360                        if (DEBUG_REMOVE && chatty) {
12361                            if (r == null) {
12362                                r = new StringBuilder(256);
12363                            } else {
12364                                r.append(' ');
12365                            }
12366                            r.append(name);
12367                        }
12368                    }
12369                }
12370            }
12371        }
12372
12373        r = null;
12374
12375        // Any package can hold static shared libraries.
12376        if (pkg.staticSharedLibName != null) {
12377            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12378                if (DEBUG_REMOVE && chatty) {
12379                    if (r == null) {
12380                        r = new StringBuilder(256);
12381                    } else {
12382                        r.append(' ');
12383                    }
12384                    r.append(pkg.staticSharedLibName);
12385                }
12386            }
12387        }
12388
12389        if (r != null) {
12390            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12391        }
12392    }
12393
12394
12395    final class ActivityIntentResolver
12396            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12397        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12398                boolean defaultOnly, int userId) {
12399            if (!sUserManager.exists(userId)) return null;
12400            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12401            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12402        }
12403
12404        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12405                int userId) {
12406            if (!sUserManager.exists(userId)) return null;
12407            mFlags = flags;
12408            return super.queryIntent(intent, resolvedType,
12409                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12410                    userId);
12411        }
12412
12413        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12414                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12415            if (!sUserManager.exists(userId)) return null;
12416            if (packageActivities == null) {
12417                return null;
12418            }
12419            mFlags = flags;
12420            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12421            final int N = packageActivities.size();
12422            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12423                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12424
12425            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12426            for (int i = 0; i < N; ++i) {
12427                intentFilters = packageActivities.get(i).intents;
12428                if (intentFilters != null && intentFilters.size() > 0) {
12429                    PackageParser.ActivityIntentInfo[] array =
12430                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12431                    intentFilters.toArray(array);
12432                    listCut.add(array);
12433                }
12434            }
12435            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12436        }
12437
12438        /**
12439         * Finds a privileged activity that matches the specified activity names.
12440         */
12441        private PackageParser.Activity findMatchingActivity(
12442                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12443            for (PackageParser.Activity sysActivity : activityList) {
12444                if (sysActivity.info.name.equals(activityInfo.name)) {
12445                    return sysActivity;
12446                }
12447                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12448                    return sysActivity;
12449                }
12450                if (sysActivity.info.targetActivity != null) {
12451                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12452                        return sysActivity;
12453                    }
12454                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12455                        return sysActivity;
12456                    }
12457                }
12458            }
12459            return null;
12460        }
12461
12462        public class IterGenerator<E> {
12463            public Iterator<E> generate(ActivityIntentInfo info) {
12464                return null;
12465            }
12466        }
12467
12468        public class ActionIterGenerator extends IterGenerator<String> {
12469            @Override
12470            public Iterator<String> generate(ActivityIntentInfo info) {
12471                return info.actionsIterator();
12472            }
12473        }
12474
12475        public class CategoriesIterGenerator extends IterGenerator<String> {
12476            @Override
12477            public Iterator<String> generate(ActivityIntentInfo info) {
12478                return info.categoriesIterator();
12479            }
12480        }
12481
12482        public class SchemesIterGenerator extends IterGenerator<String> {
12483            @Override
12484            public Iterator<String> generate(ActivityIntentInfo info) {
12485                return info.schemesIterator();
12486            }
12487        }
12488
12489        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12490            @Override
12491            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12492                return info.authoritiesIterator();
12493            }
12494        }
12495
12496        /**
12497         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12498         * MODIFIED. Do not pass in a list that should not be changed.
12499         */
12500        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12501                IterGenerator<T> generator, Iterator<T> searchIterator) {
12502            // loop through the set of actions; every one must be found in the intent filter
12503            while (searchIterator.hasNext()) {
12504                // we must have at least one filter in the list to consider a match
12505                if (intentList.size() == 0) {
12506                    break;
12507                }
12508
12509                final T searchAction = searchIterator.next();
12510
12511                // loop through the set of intent filters
12512                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12513                while (intentIter.hasNext()) {
12514                    final ActivityIntentInfo intentInfo = intentIter.next();
12515                    boolean selectionFound = false;
12516
12517                    // loop through the intent filter's selection criteria; at least one
12518                    // of them must match the searched criteria
12519                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12520                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12521                        final T intentSelection = intentSelectionIter.next();
12522                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12523                            selectionFound = true;
12524                            break;
12525                        }
12526                    }
12527
12528                    // the selection criteria wasn't found in this filter's set; this filter
12529                    // is not a potential match
12530                    if (!selectionFound) {
12531                        intentIter.remove();
12532                    }
12533                }
12534            }
12535        }
12536
12537        private boolean isProtectedAction(ActivityIntentInfo filter) {
12538            final Iterator<String> actionsIter = filter.actionsIterator();
12539            while (actionsIter != null && actionsIter.hasNext()) {
12540                final String filterAction = actionsIter.next();
12541                if (PROTECTED_ACTIONS.contains(filterAction)) {
12542                    return true;
12543                }
12544            }
12545            return false;
12546        }
12547
12548        /**
12549         * Adjusts the priority of the given intent filter according to policy.
12550         * <p>
12551         * <ul>
12552         * <li>The priority for non privileged applications is capped to '0'</li>
12553         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12554         * <li>The priority for unbundled updates to privileged applications is capped to the
12555         *      priority defined on the system partition</li>
12556         * </ul>
12557         * <p>
12558         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12559         * allowed to obtain any priority on any action.
12560         */
12561        private void adjustPriority(
12562                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12563            // nothing to do; priority is fine as-is
12564            if (intent.getPriority() <= 0) {
12565                return;
12566            }
12567
12568            final ActivityInfo activityInfo = intent.activity.info;
12569            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12570
12571            final boolean privilegedApp =
12572                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12573            if (!privilegedApp) {
12574                // non-privileged applications can never define a priority >0
12575                if (DEBUG_FILTERS) {
12576                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12577                            + " package: " + applicationInfo.packageName
12578                            + " activity: " + intent.activity.className
12579                            + " origPrio: " + intent.getPriority());
12580                }
12581                intent.setPriority(0);
12582                return;
12583            }
12584
12585            if (systemActivities == null) {
12586                // the system package is not disabled; we're parsing the system partition
12587                if (isProtectedAction(intent)) {
12588                    if (mDeferProtectedFilters) {
12589                        // We can't deal with these just yet. No component should ever obtain a
12590                        // >0 priority for a protected actions, with ONE exception -- the setup
12591                        // wizard. The setup wizard, however, cannot be known until we're able to
12592                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12593                        // until all intent filters have been processed. Chicken, meet egg.
12594                        // Let the filter temporarily have a high priority and rectify the
12595                        // priorities after all system packages have been scanned.
12596                        mProtectedFilters.add(intent);
12597                        if (DEBUG_FILTERS) {
12598                            Slog.i(TAG, "Protected action; save for later;"
12599                                    + " package: " + applicationInfo.packageName
12600                                    + " activity: " + intent.activity.className
12601                                    + " origPrio: " + intent.getPriority());
12602                        }
12603                        return;
12604                    } else {
12605                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12606                            Slog.i(TAG, "No setup wizard;"
12607                                + " All protected intents capped to priority 0");
12608                        }
12609                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12610                            if (DEBUG_FILTERS) {
12611                                Slog.i(TAG, "Found setup wizard;"
12612                                    + " allow priority " + intent.getPriority() + ";"
12613                                    + " package: " + intent.activity.info.packageName
12614                                    + " activity: " + intent.activity.className
12615                                    + " priority: " + intent.getPriority());
12616                            }
12617                            // setup wizard gets whatever it wants
12618                            return;
12619                        }
12620                        if (DEBUG_FILTERS) {
12621                            Slog.i(TAG, "Protected action; cap priority to 0;"
12622                                    + " package: " + intent.activity.info.packageName
12623                                    + " activity: " + intent.activity.className
12624                                    + " origPrio: " + intent.getPriority());
12625                        }
12626                        intent.setPriority(0);
12627                        return;
12628                    }
12629                }
12630                // privileged apps on the system image get whatever priority they request
12631                return;
12632            }
12633
12634            // privileged app unbundled update ... try to find the same activity
12635            final PackageParser.Activity foundActivity =
12636                    findMatchingActivity(systemActivities, activityInfo);
12637            if (foundActivity == null) {
12638                // this is a new activity; it cannot obtain >0 priority
12639                if (DEBUG_FILTERS) {
12640                    Slog.i(TAG, "New activity; cap priority to 0;"
12641                            + " package: " + applicationInfo.packageName
12642                            + " activity: " + intent.activity.className
12643                            + " origPrio: " + intent.getPriority());
12644                }
12645                intent.setPriority(0);
12646                return;
12647            }
12648
12649            // found activity, now check for filter equivalence
12650
12651            // a shallow copy is enough; we modify the list, not its contents
12652            final List<ActivityIntentInfo> intentListCopy =
12653                    new ArrayList<>(foundActivity.intents);
12654            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12655
12656            // find matching action subsets
12657            final Iterator<String> actionsIterator = intent.actionsIterator();
12658            if (actionsIterator != null) {
12659                getIntentListSubset(
12660                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12661                if (intentListCopy.size() == 0) {
12662                    // no more intents to match; we're not equivalent
12663                    if (DEBUG_FILTERS) {
12664                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12665                                + " package: " + applicationInfo.packageName
12666                                + " activity: " + intent.activity.className
12667                                + " origPrio: " + intent.getPriority());
12668                    }
12669                    intent.setPriority(0);
12670                    return;
12671                }
12672            }
12673
12674            // find matching category subsets
12675            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12676            if (categoriesIterator != null) {
12677                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12678                        categoriesIterator);
12679                if (intentListCopy.size() == 0) {
12680                    // no more intents to match; we're not equivalent
12681                    if (DEBUG_FILTERS) {
12682                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12683                                + " package: " + applicationInfo.packageName
12684                                + " activity: " + intent.activity.className
12685                                + " origPrio: " + intent.getPriority());
12686                    }
12687                    intent.setPriority(0);
12688                    return;
12689                }
12690            }
12691
12692            // find matching schemes subsets
12693            final Iterator<String> schemesIterator = intent.schemesIterator();
12694            if (schemesIterator != null) {
12695                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12696                        schemesIterator);
12697                if (intentListCopy.size() == 0) {
12698                    // no more intents to match; we're not equivalent
12699                    if (DEBUG_FILTERS) {
12700                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12701                                + " package: " + applicationInfo.packageName
12702                                + " activity: " + intent.activity.className
12703                                + " origPrio: " + intent.getPriority());
12704                    }
12705                    intent.setPriority(0);
12706                    return;
12707                }
12708            }
12709
12710            // find matching authorities subsets
12711            final Iterator<IntentFilter.AuthorityEntry>
12712                    authoritiesIterator = intent.authoritiesIterator();
12713            if (authoritiesIterator != null) {
12714                getIntentListSubset(intentListCopy,
12715                        new AuthoritiesIterGenerator(),
12716                        authoritiesIterator);
12717                if (intentListCopy.size() == 0) {
12718                    // no more intents to match; we're not equivalent
12719                    if (DEBUG_FILTERS) {
12720                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12721                                + " package: " + applicationInfo.packageName
12722                                + " activity: " + intent.activity.className
12723                                + " origPrio: " + intent.getPriority());
12724                    }
12725                    intent.setPriority(0);
12726                    return;
12727                }
12728            }
12729
12730            // we found matching filter(s); app gets the max priority of all intents
12731            int cappedPriority = 0;
12732            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12733                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12734            }
12735            if (intent.getPriority() > cappedPriority) {
12736                if (DEBUG_FILTERS) {
12737                    Slog.i(TAG, "Found matching filter(s);"
12738                            + " cap priority to " + cappedPriority + ";"
12739                            + " package: " + applicationInfo.packageName
12740                            + " activity: " + intent.activity.className
12741                            + " origPrio: " + intent.getPriority());
12742                }
12743                intent.setPriority(cappedPriority);
12744                return;
12745            }
12746            // all this for nothing; the requested priority was <= what was on the system
12747        }
12748
12749        public final void addActivity(PackageParser.Activity a, String type) {
12750            mActivities.put(a.getComponentName(), a);
12751            if (DEBUG_SHOW_INFO)
12752                Log.v(
12753                TAG, "  " + type + " " +
12754                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12755            if (DEBUG_SHOW_INFO)
12756                Log.v(TAG, "    Class=" + a.info.name);
12757            final int NI = a.intents.size();
12758            for (int j=0; j<NI; j++) {
12759                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12760                if ("activity".equals(type)) {
12761                    final PackageSetting ps =
12762                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12763                    final List<PackageParser.Activity> systemActivities =
12764                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12765                    adjustPriority(systemActivities, intent);
12766                }
12767                if (DEBUG_SHOW_INFO) {
12768                    Log.v(TAG, "    IntentFilter:");
12769                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12770                }
12771                if (!intent.debugCheck()) {
12772                    Log.w(TAG, "==> For Activity " + a.info.name);
12773                }
12774                addFilter(intent);
12775            }
12776        }
12777
12778        public final void removeActivity(PackageParser.Activity a, String type) {
12779            mActivities.remove(a.getComponentName());
12780            if (DEBUG_SHOW_INFO) {
12781                Log.v(TAG, "  " + type + " "
12782                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12783                                : a.info.name) + ":");
12784                Log.v(TAG, "    Class=" + a.info.name);
12785            }
12786            final int NI = a.intents.size();
12787            for (int j=0; j<NI; j++) {
12788                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12789                if (DEBUG_SHOW_INFO) {
12790                    Log.v(TAG, "    IntentFilter:");
12791                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12792                }
12793                removeFilter(intent);
12794            }
12795        }
12796
12797        @Override
12798        protected boolean allowFilterResult(
12799                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12800            ActivityInfo filterAi = filter.activity.info;
12801            for (int i=dest.size()-1; i>=0; i--) {
12802                ActivityInfo destAi = dest.get(i).activityInfo;
12803                if (destAi.name == filterAi.name
12804                        && destAi.packageName == filterAi.packageName) {
12805                    return false;
12806                }
12807            }
12808            return true;
12809        }
12810
12811        @Override
12812        protected ActivityIntentInfo[] newArray(int size) {
12813            return new ActivityIntentInfo[size];
12814        }
12815
12816        @Override
12817        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12818            if (!sUserManager.exists(userId)) return true;
12819            PackageParser.Package p = filter.activity.owner;
12820            if (p != null) {
12821                PackageSetting ps = (PackageSetting)p.mExtras;
12822                if (ps != null) {
12823                    // System apps are never considered stopped for purposes of
12824                    // filtering, because there may be no way for the user to
12825                    // actually re-launch them.
12826                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12827                            && ps.getStopped(userId);
12828                }
12829            }
12830            return false;
12831        }
12832
12833        @Override
12834        protected boolean isPackageForFilter(String packageName,
12835                PackageParser.ActivityIntentInfo info) {
12836            return packageName.equals(info.activity.owner.packageName);
12837        }
12838
12839        @Override
12840        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12841                int match, int userId) {
12842            if (!sUserManager.exists(userId)) return null;
12843            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12844                return null;
12845            }
12846            final PackageParser.Activity activity = info.activity;
12847            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12848            if (ps == null) {
12849                return null;
12850            }
12851            final PackageUserState userState = ps.readUserState(userId);
12852            ActivityInfo ai =
12853                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12854            if (ai == null) {
12855                return null;
12856            }
12857            final boolean matchExplicitlyVisibleOnly =
12858                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12859            final boolean matchVisibleToInstantApp =
12860                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12861            final boolean componentVisible =
12862                    matchVisibleToInstantApp
12863                    && info.isVisibleToInstantApp()
12864                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12865            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12866            // throw out filters that aren't visible to ephemeral apps
12867            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12868                return null;
12869            }
12870            // throw out instant app filters if we're not explicitly requesting them
12871            if (!matchInstantApp && userState.instantApp) {
12872                return null;
12873            }
12874            // throw out instant app filters if updates are available; will trigger
12875            // instant app resolution
12876            if (userState.instantApp && ps.isUpdateAvailable()) {
12877                return null;
12878            }
12879            final ResolveInfo res = new ResolveInfo();
12880            res.activityInfo = ai;
12881            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12882                res.filter = info;
12883            }
12884            if (info != null) {
12885                res.handleAllWebDataURI = info.handleAllWebDataURI();
12886            }
12887            res.priority = info.getPriority();
12888            res.preferredOrder = activity.owner.mPreferredOrder;
12889            //System.out.println("Result: " + res.activityInfo.className +
12890            //                   " = " + res.priority);
12891            res.match = match;
12892            res.isDefault = info.hasDefault;
12893            res.labelRes = info.labelRes;
12894            res.nonLocalizedLabel = info.nonLocalizedLabel;
12895            if (userNeedsBadging(userId)) {
12896                res.noResourceId = true;
12897            } else {
12898                res.icon = info.icon;
12899            }
12900            res.iconResourceId = info.icon;
12901            res.system = res.activityInfo.applicationInfo.isSystemApp();
12902            res.isInstantAppAvailable = userState.instantApp;
12903            return res;
12904        }
12905
12906        @Override
12907        protected void sortResults(List<ResolveInfo> results) {
12908            Collections.sort(results, mResolvePrioritySorter);
12909        }
12910
12911        @Override
12912        protected void dumpFilter(PrintWriter out, String prefix,
12913                PackageParser.ActivityIntentInfo filter) {
12914            out.print(prefix); out.print(
12915                    Integer.toHexString(System.identityHashCode(filter.activity)));
12916                    out.print(' ');
12917                    filter.activity.printComponentShortName(out);
12918                    out.print(" filter ");
12919                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12920        }
12921
12922        @Override
12923        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12924            return filter.activity;
12925        }
12926
12927        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12928            PackageParser.Activity activity = (PackageParser.Activity)label;
12929            out.print(prefix); out.print(
12930                    Integer.toHexString(System.identityHashCode(activity)));
12931                    out.print(' ');
12932                    activity.printComponentShortName(out);
12933            if (count > 1) {
12934                out.print(" ("); out.print(count); out.print(" filters)");
12935            }
12936            out.println();
12937        }
12938
12939        // Keys are String (activity class name), values are Activity.
12940        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12941                = new ArrayMap<ComponentName, PackageParser.Activity>();
12942        private int mFlags;
12943    }
12944
12945    private final class ServiceIntentResolver
12946            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12947        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12948                boolean defaultOnly, int userId) {
12949            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12950            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12951        }
12952
12953        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12954                int userId) {
12955            if (!sUserManager.exists(userId)) return null;
12956            mFlags = flags;
12957            return super.queryIntent(intent, resolvedType,
12958                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12959                    userId);
12960        }
12961
12962        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12963                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12964            if (!sUserManager.exists(userId)) return null;
12965            if (packageServices == null) {
12966                return null;
12967            }
12968            mFlags = flags;
12969            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12970            final int N = packageServices.size();
12971            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12972                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12973
12974            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12975            for (int i = 0; i < N; ++i) {
12976                intentFilters = packageServices.get(i).intents;
12977                if (intentFilters != null && intentFilters.size() > 0) {
12978                    PackageParser.ServiceIntentInfo[] array =
12979                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12980                    intentFilters.toArray(array);
12981                    listCut.add(array);
12982                }
12983            }
12984            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12985        }
12986
12987        public final void addService(PackageParser.Service s) {
12988            mServices.put(s.getComponentName(), s);
12989            if (DEBUG_SHOW_INFO) {
12990                Log.v(TAG, "  "
12991                        + (s.info.nonLocalizedLabel != null
12992                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12993                Log.v(TAG, "    Class=" + s.info.name);
12994            }
12995            final int NI = s.intents.size();
12996            int j;
12997            for (j=0; j<NI; j++) {
12998                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12999                if (DEBUG_SHOW_INFO) {
13000                    Log.v(TAG, "    IntentFilter:");
13001                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13002                }
13003                if (!intent.debugCheck()) {
13004                    Log.w(TAG, "==> For Service " + s.info.name);
13005                }
13006                addFilter(intent);
13007            }
13008        }
13009
13010        public final void removeService(PackageParser.Service s) {
13011            mServices.remove(s.getComponentName());
13012            if (DEBUG_SHOW_INFO) {
13013                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13014                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13015                Log.v(TAG, "    Class=" + s.info.name);
13016            }
13017            final int NI = s.intents.size();
13018            int j;
13019            for (j=0; j<NI; j++) {
13020                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13021                if (DEBUG_SHOW_INFO) {
13022                    Log.v(TAG, "    IntentFilter:");
13023                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13024                }
13025                removeFilter(intent);
13026            }
13027        }
13028
13029        @Override
13030        protected boolean allowFilterResult(
13031                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13032            ServiceInfo filterSi = filter.service.info;
13033            for (int i=dest.size()-1; i>=0; i--) {
13034                ServiceInfo destAi = dest.get(i).serviceInfo;
13035                if (destAi.name == filterSi.name
13036                        && destAi.packageName == filterSi.packageName) {
13037                    return false;
13038                }
13039            }
13040            return true;
13041        }
13042
13043        @Override
13044        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13045            return new PackageParser.ServiceIntentInfo[size];
13046        }
13047
13048        @Override
13049        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13050            if (!sUserManager.exists(userId)) return true;
13051            PackageParser.Package p = filter.service.owner;
13052            if (p != null) {
13053                PackageSetting ps = (PackageSetting)p.mExtras;
13054                if (ps != null) {
13055                    // System apps are never considered stopped for purposes of
13056                    // filtering, because there may be no way for the user to
13057                    // actually re-launch them.
13058                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13059                            && ps.getStopped(userId);
13060                }
13061            }
13062            return false;
13063        }
13064
13065        @Override
13066        protected boolean isPackageForFilter(String packageName,
13067                PackageParser.ServiceIntentInfo info) {
13068            return packageName.equals(info.service.owner.packageName);
13069        }
13070
13071        @Override
13072        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13073                int match, int userId) {
13074            if (!sUserManager.exists(userId)) return null;
13075            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13076            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13077                return null;
13078            }
13079            final PackageParser.Service service = info.service;
13080            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13081            if (ps == null) {
13082                return null;
13083            }
13084            final PackageUserState userState = ps.readUserState(userId);
13085            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13086                    userState, userId);
13087            if (si == null) {
13088                return null;
13089            }
13090            final boolean matchVisibleToInstantApp =
13091                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13092            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13093            // throw out filters that aren't visible to ephemeral apps
13094            if (matchVisibleToInstantApp
13095                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13096                return null;
13097            }
13098            // throw out ephemeral filters if we're not explicitly requesting them
13099            if (!isInstantApp && userState.instantApp) {
13100                return null;
13101            }
13102            // throw out instant app filters if updates are available; will trigger
13103            // instant app resolution
13104            if (userState.instantApp && ps.isUpdateAvailable()) {
13105                return null;
13106            }
13107            final ResolveInfo res = new ResolveInfo();
13108            res.serviceInfo = si;
13109            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13110                res.filter = filter;
13111            }
13112            res.priority = info.getPriority();
13113            res.preferredOrder = service.owner.mPreferredOrder;
13114            res.match = match;
13115            res.isDefault = info.hasDefault;
13116            res.labelRes = info.labelRes;
13117            res.nonLocalizedLabel = info.nonLocalizedLabel;
13118            res.icon = info.icon;
13119            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13120            return res;
13121        }
13122
13123        @Override
13124        protected void sortResults(List<ResolveInfo> results) {
13125            Collections.sort(results, mResolvePrioritySorter);
13126        }
13127
13128        @Override
13129        protected void dumpFilter(PrintWriter out, String prefix,
13130                PackageParser.ServiceIntentInfo filter) {
13131            out.print(prefix); out.print(
13132                    Integer.toHexString(System.identityHashCode(filter.service)));
13133                    out.print(' ');
13134                    filter.service.printComponentShortName(out);
13135                    out.print(" filter ");
13136                    out.print(Integer.toHexString(System.identityHashCode(filter)));
13137                    if (filter.service.info.permission != null) {
13138                        out.print(" permission "); out.println(filter.service.info.permission);
13139                    } else {
13140                        out.println();
13141                    }
13142        }
13143
13144        @Override
13145        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13146            return filter.service;
13147        }
13148
13149        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13150            PackageParser.Service service = (PackageParser.Service)label;
13151            out.print(prefix); out.print(
13152                    Integer.toHexString(System.identityHashCode(service)));
13153                    out.print(' ');
13154                    service.printComponentShortName(out);
13155            if (count > 1) {
13156                out.print(" ("); out.print(count); out.print(" filters)");
13157            }
13158            out.println();
13159        }
13160
13161//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13162//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13163//            final List<ResolveInfo> retList = Lists.newArrayList();
13164//            while (i.hasNext()) {
13165//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13166//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13167//                    retList.add(resolveInfo);
13168//                }
13169//            }
13170//            return retList;
13171//        }
13172
13173        // Keys are String (activity class name), values are Activity.
13174        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13175                = new ArrayMap<ComponentName, PackageParser.Service>();
13176        private int mFlags;
13177    }
13178
13179    private final class ProviderIntentResolver
13180            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13181        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13182                boolean defaultOnly, int userId) {
13183            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13184            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13185        }
13186
13187        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13188                int userId) {
13189            if (!sUserManager.exists(userId))
13190                return null;
13191            mFlags = flags;
13192            return super.queryIntent(intent, resolvedType,
13193                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13194                    userId);
13195        }
13196
13197        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13198                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13199            if (!sUserManager.exists(userId))
13200                return null;
13201            if (packageProviders == null) {
13202                return null;
13203            }
13204            mFlags = flags;
13205            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13206            final int N = packageProviders.size();
13207            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13208                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13209
13210            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13211            for (int i = 0; i < N; ++i) {
13212                intentFilters = packageProviders.get(i).intents;
13213                if (intentFilters != null && intentFilters.size() > 0) {
13214                    PackageParser.ProviderIntentInfo[] array =
13215                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13216                    intentFilters.toArray(array);
13217                    listCut.add(array);
13218                }
13219            }
13220            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13221        }
13222
13223        public final void addProvider(PackageParser.Provider p) {
13224            if (mProviders.containsKey(p.getComponentName())) {
13225                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13226                return;
13227            }
13228
13229            mProviders.put(p.getComponentName(), p);
13230            if (DEBUG_SHOW_INFO) {
13231                Log.v(TAG, "  "
13232                        + (p.info.nonLocalizedLabel != null
13233                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13234                Log.v(TAG, "    Class=" + p.info.name);
13235            }
13236            final int NI = p.intents.size();
13237            int j;
13238            for (j = 0; j < NI; j++) {
13239                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13240                if (DEBUG_SHOW_INFO) {
13241                    Log.v(TAG, "    IntentFilter:");
13242                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13243                }
13244                if (!intent.debugCheck()) {
13245                    Log.w(TAG, "==> For Provider " + p.info.name);
13246                }
13247                addFilter(intent);
13248            }
13249        }
13250
13251        public final void removeProvider(PackageParser.Provider p) {
13252            mProviders.remove(p.getComponentName());
13253            if (DEBUG_SHOW_INFO) {
13254                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13255                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13256                Log.v(TAG, "    Class=" + p.info.name);
13257            }
13258            final int NI = p.intents.size();
13259            int j;
13260            for (j = 0; j < NI; j++) {
13261                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13262                if (DEBUG_SHOW_INFO) {
13263                    Log.v(TAG, "    IntentFilter:");
13264                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13265                }
13266                removeFilter(intent);
13267            }
13268        }
13269
13270        @Override
13271        protected boolean allowFilterResult(
13272                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13273            ProviderInfo filterPi = filter.provider.info;
13274            for (int i = dest.size() - 1; i >= 0; i--) {
13275                ProviderInfo destPi = dest.get(i).providerInfo;
13276                if (destPi.name == filterPi.name
13277                        && destPi.packageName == filterPi.packageName) {
13278                    return false;
13279                }
13280            }
13281            return true;
13282        }
13283
13284        @Override
13285        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13286            return new PackageParser.ProviderIntentInfo[size];
13287        }
13288
13289        @Override
13290        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13291            if (!sUserManager.exists(userId))
13292                return true;
13293            PackageParser.Package p = filter.provider.owner;
13294            if (p != null) {
13295                PackageSetting ps = (PackageSetting) p.mExtras;
13296                if (ps != null) {
13297                    // System apps are never considered stopped for purposes of
13298                    // filtering, because there may be no way for the user to
13299                    // actually re-launch them.
13300                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13301                            && ps.getStopped(userId);
13302                }
13303            }
13304            return false;
13305        }
13306
13307        @Override
13308        protected boolean isPackageForFilter(String packageName,
13309                PackageParser.ProviderIntentInfo info) {
13310            return packageName.equals(info.provider.owner.packageName);
13311        }
13312
13313        @Override
13314        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13315                int match, int userId) {
13316            if (!sUserManager.exists(userId))
13317                return null;
13318            final PackageParser.ProviderIntentInfo info = filter;
13319            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13320                return null;
13321            }
13322            final PackageParser.Provider provider = info.provider;
13323            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13324            if (ps == null) {
13325                return null;
13326            }
13327            final PackageUserState userState = ps.readUserState(userId);
13328            final boolean matchVisibleToInstantApp =
13329                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13330            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13331            // throw out filters that aren't visible to instant applications
13332            if (matchVisibleToInstantApp
13333                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13334                return null;
13335            }
13336            // throw out instant application filters if we're not explicitly requesting them
13337            if (!isInstantApp && userState.instantApp) {
13338                return null;
13339            }
13340            // throw out instant application filters if updates are available; will trigger
13341            // instant application resolution
13342            if (userState.instantApp && ps.isUpdateAvailable()) {
13343                return null;
13344            }
13345            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13346                    userState, userId);
13347            if (pi == null) {
13348                return null;
13349            }
13350            final ResolveInfo res = new ResolveInfo();
13351            res.providerInfo = pi;
13352            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13353                res.filter = filter;
13354            }
13355            res.priority = info.getPriority();
13356            res.preferredOrder = provider.owner.mPreferredOrder;
13357            res.match = match;
13358            res.isDefault = info.hasDefault;
13359            res.labelRes = info.labelRes;
13360            res.nonLocalizedLabel = info.nonLocalizedLabel;
13361            res.icon = info.icon;
13362            res.system = res.providerInfo.applicationInfo.isSystemApp();
13363            return res;
13364        }
13365
13366        @Override
13367        protected void sortResults(List<ResolveInfo> results) {
13368            Collections.sort(results, mResolvePrioritySorter);
13369        }
13370
13371        @Override
13372        protected void dumpFilter(PrintWriter out, String prefix,
13373                PackageParser.ProviderIntentInfo filter) {
13374            out.print(prefix);
13375            out.print(
13376                    Integer.toHexString(System.identityHashCode(filter.provider)));
13377            out.print(' ');
13378            filter.provider.printComponentShortName(out);
13379            out.print(" filter ");
13380            out.println(Integer.toHexString(System.identityHashCode(filter)));
13381        }
13382
13383        @Override
13384        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13385            return filter.provider;
13386        }
13387
13388        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13389            PackageParser.Provider provider = (PackageParser.Provider)label;
13390            out.print(prefix); out.print(
13391                    Integer.toHexString(System.identityHashCode(provider)));
13392                    out.print(' ');
13393                    provider.printComponentShortName(out);
13394            if (count > 1) {
13395                out.print(" ("); out.print(count); out.print(" filters)");
13396            }
13397            out.println();
13398        }
13399
13400        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13401                = new ArrayMap<ComponentName, PackageParser.Provider>();
13402        private int mFlags;
13403    }
13404
13405    static final class InstantAppIntentResolver
13406            extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter,
13407            AuxiliaryResolveInfo.AuxiliaryFilter> {
13408        /**
13409         * The result that has the highest defined order. Ordering applies on a
13410         * per-package basis. Mapping is from package name to Pair of order and
13411         * EphemeralResolveInfo.
13412         * <p>
13413         * NOTE: This is implemented as a field variable for convenience and efficiency.
13414         * By having a field variable, we're able to track filter ordering as soon as
13415         * a non-zero order is defined. Otherwise, multiple loops across the result set
13416         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13417         * this needs to be contained entirely within {@link #filterResults}.
13418         */
13419        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13420
13421        @Override
13422        protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) {
13423            return new AuxiliaryResolveInfo.AuxiliaryFilter[size];
13424        }
13425
13426        @Override
13427        protected boolean isPackageForFilter(String packageName,
13428                AuxiliaryResolveInfo.AuxiliaryFilter responseObj) {
13429            return true;
13430        }
13431
13432        @Override
13433        protected AuxiliaryResolveInfo.AuxiliaryFilter newResult(
13434                AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) {
13435            if (!sUserManager.exists(userId)) {
13436                return null;
13437            }
13438            final String packageName = responseObj.resolveInfo.getPackageName();
13439            final Integer order = responseObj.getOrder();
13440            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13441                    mOrderResult.get(packageName);
13442            // ordering is enabled and this item's order isn't high enough
13443            if (lastOrderResult != null && lastOrderResult.first >= order) {
13444                return null;
13445            }
13446            final InstantAppResolveInfo res = responseObj.resolveInfo;
13447            if (order > 0) {
13448                // non-zero order, enable ordering
13449                mOrderResult.put(packageName, new Pair<>(order, res));
13450            }
13451            return responseObj;
13452        }
13453
13454        @Override
13455        protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) {
13456            // only do work if ordering is enabled [most of the time it won't be]
13457            if (mOrderResult.size() == 0) {
13458                return;
13459            }
13460            int resultSize = results.size();
13461            for (int i = 0; i < resultSize; i++) {
13462                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13463                final String packageName = info.getPackageName();
13464                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13465                if (savedInfo == null) {
13466                    // package doesn't having ordering
13467                    continue;
13468                }
13469                if (savedInfo.second == info) {
13470                    // circled back to the highest ordered item; remove from order list
13471                    mOrderResult.remove(packageName);
13472                    if (mOrderResult.size() == 0) {
13473                        // no more ordered items
13474                        break;
13475                    }
13476                    continue;
13477                }
13478                // item has a worse order, remove it from the result list
13479                results.remove(i);
13480                resultSize--;
13481                i--;
13482            }
13483        }
13484    }
13485
13486    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13487            new Comparator<ResolveInfo>() {
13488        public int compare(ResolveInfo r1, ResolveInfo r2) {
13489            int v1 = r1.priority;
13490            int v2 = r2.priority;
13491            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13492            if (v1 != v2) {
13493                return (v1 > v2) ? -1 : 1;
13494            }
13495            v1 = r1.preferredOrder;
13496            v2 = r2.preferredOrder;
13497            if (v1 != v2) {
13498                return (v1 > v2) ? -1 : 1;
13499            }
13500            if (r1.isDefault != r2.isDefault) {
13501                return r1.isDefault ? -1 : 1;
13502            }
13503            v1 = r1.match;
13504            v2 = r2.match;
13505            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13506            if (v1 != v2) {
13507                return (v1 > v2) ? -1 : 1;
13508            }
13509            if (r1.system != r2.system) {
13510                return r1.system ? -1 : 1;
13511            }
13512            if (r1.activityInfo != null) {
13513                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13514            }
13515            if (r1.serviceInfo != null) {
13516                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13517            }
13518            if (r1.providerInfo != null) {
13519                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13520            }
13521            return 0;
13522        }
13523    };
13524
13525    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13526            new Comparator<ProviderInfo>() {
13527        public int compare(ProviderInfo p1, ProviderInfo p2) {
13528            final int v1 = p1.initOrder;
13529            final int v2 = p2.initOrder;
13530            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13531        }
13532    };
13533
13534    @Override
13535    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13536            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13537            final int[] userIds, int[] instantUserIds) {
13538        mHandler.post(new Runnable() {
13539            @Override
13540            public void run() {
13541                try {
13542                    final IActivityManager am = ActivityManager.getService();
13543                    if (am == null) return;
13544                    final int[] resolvedUserIds;
13545                    if (userIds == null) {
13546                        resolvedUserIds = am.getRunningUserIds();
13547                    } else {
13548                        resolvedUserIds = userIds;
13549                    }
13550                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13551                            resolvedUserIds, false);
13552                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
13553                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13554                                instantUserIds, true);
13555                    }
13556                } catch (RemoteException ex) {
13557                }
13558            }
13559        });
13560    }
13561
13562    @Override
13563    public void notifyPackageAdded(String packageName) {
13564        final PackageListObserver[] observers;
13565        synchronized (mPackages) {
13566            if (mPackageListObservers.size() == 0) {
13567                return;
13568            }
13569            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13570        }
13571        for (int i = observers.length - 1; i >= 0; --i) {
13572            observers[i].onPackageAdded(packageName);
13573        }
13574    }
13575
13576    @Override
13577    public void notifyPackageRemoved(String packageName) {
13578        final PackageListObserver[] observers;
13579        synchronized (mPackages) {
13580            if (mPackageListObservers.size() == 0) {
13581                return;
13582            }
13583            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13584        }
13585        for (int i = observers.length - 1; i >= 0; --i) {
13586            observers[i].onPackageRemoved(packageName);
13587        }
13588    }
13589
13590    /**
13591     * Sends a broadcast for the given action.
13592     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13593     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13594     * the system and applications allowed to see instant applications to receive package
13595     * lifecycle events for instant applications.
13596     */
13597    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13598            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13599            int[] userIds, boolean isInstantApp)
13600                    throws RemoteException {
13601        for (int id : userIds) {
13602            final Intent intent = new Intent(action,
13603                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13604            final String[] requiredPermissions =
13605                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13606            if (extras != null) {
13607                intent.putExtras(extras);
13608            }
13609            if (targetPkg != null) {
13610                intent.setPackage(targetPkg);
13611            }
13612            // Modify the UID when posting to other users
13613            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13614            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13615                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13616                intent.putExtra(Intent.EXTRA_UID, uid);
13617            }
13618            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13619            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13620            if (DEBUG_BROADCASTS) {
13621                RuntimeException here = new RuntimeException("here");
13622                here.fillInStackTrace();
13623                Slog.d(TAG, "Sending to user " + id + ": "
13624                        + intent.toShortString(false, true, false, false)
13625                        + " " + intent.getExtras(), here);
13626            }
13627            am.broadcastIntent(null, intent, null, finishedReceiver,
13628                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13629                    null, finishedReceiver != null, false, id);
13630        }
13631    }
13632
13633    /**
13634     * Check if the external storage media is available. This is true if there
13635     * is a mounted external storage medium or if the external storage is
13636     * emulated.
13637     */
13638    private boolean isExternalMediaAvailable() {
13639        return mMediaMounted || Environment.isExternalStorageEmulated();
13640    }
13641
13642    @Override
13643    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13644        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13645            return null;
13646        }
13647        if (!isExternalMediaAvailable()) {
13648                // If the external storage is no longer mounted at this point,
13649                // the caller may not have been able to delete all of this
13650                // packages files and can not delete any more.  Bail.
13651            return null;
13652        }
13653        synchronized (mPackages) {
13654            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13655            if (lastPackage != null) {
13656                pkgs.remove(lastPackage);
13657            }
13658            if (pkgs.size() > 0) {
13659                return pkgs.get(0);
13660            }
13661        }
13662        return null;
13663    }
13664
13665    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13666        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13667                userId, andCode ? 1 : 0, packageName);
13668        if (mSystemReady) {
13669            msg.sendToTarget();
13670        } else {
13671            if (mPostSystemReadyMessages == null) {
13672                mPostSystemReadyMessages = new ArrayList<>();
13673            }
13674            mPostSystemReadyMessages.add(msg);
13675        }
13676    }
13677
13678    void startCleaningPackages() {
13679        // reader
13680        if (!isExternalMediaAvailable()) {
13681            return;
13682        }
13683        synchronized (mPackages) {
13684            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13685                return;
13686            }
13687        }
13688        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13689        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13690        IActivityManager am = ActivityManager.getService();
13691        if (am != null) {
13692            int dcsUid = -1;
13693            synchronized (mPackages) {
13694                if (!mDefaultContainerWhitelisted) {
13695                    mDefaultContainerWhitelisted = true;
13696                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13697                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13698                }
13699            }
13700            try {
13701                if (dcsUid > 0) {
13702                    am.backgroundWhitelistUid(dcsUid);
13703                }
13704                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13705                        UserHandle.USER_SYSTEM);
13706            } catch (RemoteException e) {
13707            }
13708        }
13709    }
13710
13711    /**
13712     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13713     * it is acting on behalf on an enterprise or the user).
13714     *
13715     * Note that the ordering of the conditionals in this method is important. The checks we perform
13716     * are as follows, in this order:
13717     *
13718     * 1) If the install is being performed by a system app, we can trust the app to have set the
13719     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13720     *    what it is.
13721     * 2) If the install is being performed by a device or profile owner app, the install reason
13722     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13723     *    set the install reason correctly. If the app targets an older SDK version where install
13724     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13725     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13726     * 3) In all other cases, the install is being performed by a regular app that is neither part
13727     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13728     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13729     *    set to enterprise policy and if so, change it to unknown instead.
13730     */
13731    private int fixUpInstallReason(String installerPackageName, int installerUid,
13732            int installReason) {
13733        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13734                == PERMISSION_GRANTED) {
13735            // If the install is being performed by a system app, we trust that app to have set the
13736            // install reason correctly.
13737            return installReason;
13738        }
13739        final String ownerPackage = mProtectedPackages.getDeviceOwnerOrProfileOwnerPackage(
13740                UserHandle.getUserId(installerUid));
13741        if (ownerPackage != null && ownerPackage.equals(installerPackageName)) {
13742            // If the install is being performed by a device or profile owner, the install
13743            // reason should be enterprise policy.
13744            return PackageManager.INSTALL_REASON_POLICY;
13745        }
13746
13747
13748        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13749            // If the install is being performed by a regular app (i.e. neither system app nor
13750            // device or profile owner), we have no reason to believe that the app is acting on
13751            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13752            // change it to unknown instead.
13753            return PackageManager.INSTALL_REASON_UNKNOWN;
13754        }
13755
13756        // If the install is being performed by a regular app and the install reason was set to any
13757        // value but enterprise policy, leave the install reason unchanged.
13758        return installReason;
13759    }
13760
13761    /**
13762     * Attempts to bind to the default container service explicitly instead of doing so lazily on
13763     * install commit.
13764     */
13765    void earlyBindToDefContainer() {
13766        mHandler.sendMessage(mHandler.obtainMessage(DEF_CONTAINER_BIND));
13767    }
13768
13769    void installStage(String packageName, File stagedDir,
13770            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13771            String installerPackageName, int installerUid, UserHandle user,
13772            PackageParser.SigningDetails signingDetails) {
13773        if (DEBUG_INSTANT) {
13774            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13775                Slog.d(TAG, "Ephemeral install of " + packageName);
13776            }
13777        }
13778        final VerificationInfo verificationInfo = new VerificationInfo(
13779                sessionParams.originatingUri, sessionParams.referrerUri,
13780                sessionParams.originatingUid, installerUid);
13781
13782        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13783
13784        final Message msg = mHandler.obtainMessage(INIT_COPY);
13785        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13786                sessionParams.installReason);
13787        final InstallParams params = new InstallParams(origin, null, observer,
13788                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13789                verificationInfo, user, sessionParams.abiOverride,
13790                sessionParams.grantedRuntimePermissions, signingDetails, installReason);
13791        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13792        msg.obj = params;
13793
13794        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13795                System.identityHashCode(msg.obj));
13796        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13797                System.identityHashCode(msg.obj));
13798
13799        mHandler.sendMessage(msg);
13800    }
13801
13802    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13803            int userId) {
13804        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13805        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13806        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13807        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13808        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13809                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13810
13811        // Send a session commit broadcast
13812        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13813        info.installReason = pkgSetting.getInstallReason(userId);
13814        info.appPackageName = packageName;
13815        sendSessionCommitBroadcast(info, userId);
13816    }
13817
13818    @Override
13819    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13820            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13821        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13822            return;
13823        }
13824        Bundle extras = new Bundle(1);
13825        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13826        final int uid = UserHandle.getUid(
13827                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13828        extras.putInt(Intent.EXTRA_UID, uid);
13829
13830        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13831                packageName, extras, 0, null, null, userIds, instantUserIds);
13832        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13833            mHandler.post(() -> {
13834                        for (int userId : userIds) {
13835                            sendBootCompletedBroadcastToSystemApp(
13836                                    packageName, includeStopped, userId);
13837                        }
13838                    }
13839            );
13840        }
13841    }
13842
13843    /**
13844     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13845     * automatically without needing an explicit launch.
13846     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13847     */
13848    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13849            int userId) {
13850        // If user is not running, the app didn't miss any broadcast
13851        if (!mUserManagerInternal.isUserRunning(userId)) {
13852            return;
13853        }
13854        final IActivityManager am = ActivityManager.getService();
13855        try {
13856            // Deliver LOCKED_BOOT_COMPLETED first
13857            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13858                    .setPackage(packageName);
13859            if (includeStopped) {
13860                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13861            }
13862            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13863            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13864                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13865
13866            // Deliver BOOT_COMPLETED only if user is unlocked
13867            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13868                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13869                if (includeStopped) {
13870                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13871                }
13872                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13873                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13874            }
13875        } catch (RemoteException e) {
13876            throw e.rethrowFromSystemServer();
13877        }
13878    }
13879
13880    @Override
13881    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13882            int userId) {
13883        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13884        PackageSetting pkgSetting;
13885        final int callingUid = Binder.getCallingUid();
13886        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13887                true /* requireFullPermission */, true /* checkShell */,
13888                "setApplicationHiddenSetting for user " + userId);
13889
13890        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13891            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13892            return false;
13893        }
13894
13895        long callingId = Binder.clearCallingIdentity();
13896        try {
13897            boolean sendAdded = false;
13898            boolean sendRemoved = false;
13899            // writer
13900            synchronized (mPackages) {
13901                pkgSetting = mSettings.mPackages.get(packageName);
13902                if (pkgSetting == null) {
13903                    return false;
13904                }
13905                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13906                    return false;
13907                }
13908                // Do not allow "android" is being disabled
13909                if ("android".equals(packageName)) {
13910                    Slog.w(TAG, "Cannot hide package: android");
13911                    return false;
13912                }
13913                // Cannot hide static shared libs as they are considered
13914                // a part of the using app (emulating static linking). Also
13915                // static libs are installed always on internal storage.
13916                PackageParser.Package pkg = mPackages.get(packageName);
13917                if (pkg != null && pkg.staticSharedLibName != null) {
13918                    Slog.w(TAG, "Cannot hide package: " + packageName
13919                            + " providing static shared library: "
13920                            + pkg.staticSharedLibName);
13921                    return false;
13922                }
13923                // Only allow protected packages to hide themselves.
13924                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13925                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13926                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13927                    return false;
13928                }
13929
13930                if (pkgSetting.getHidden(userId) != hidden) {
13931                    pkgSetting.setHidden(hidden, userId);
13932                    mSettings.writePackageRestrictionsLPr(userId);
13933                    if (hidden) {
13934                        sendRemoved = true;
13935                    } else {
13936                        sendAdded = true;
13937                    }
13938                }
13939            }
13940            if (sendAdded) {
13941                sendPackageAddedForUser(packageName, pkgSetting, userId);
13942                return true;
13943            }
13944            if (sendRemoved) {
13945                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13946                        "hiding pkg");
13947                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13948                return true;
13949            }
13950        } finally {
13951            Binder.restoreCallingIdentity(callingId);
13952        }
13953        return false;
13954    }
13955
13956    @Override
13957    public boolean setSystemAppInstallState(String packageName, boolean installed, int userId) {
13958        enforceSystemOrPhoneCaller("setSystemAppInstallState");
13959        PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13960        // The target app should always be in system
13961        if (pkgSetting == null || !pkgSetting.isSystem()) {
13962            return false;
13963        }
13964        // Check if the install state is the same
13965        if (pkgSetting.getInstalled(userId) == installed) {
13966            return false;
13967        }
13968
13969        long callingId = Binder.clearCallingIdentity();
13970        try {
13971            if (installed) {
13972                // install the app from uninstalled state
13973                installExistingPackageAsUser(
13974                        packageName,
13975                        userId,
13976                        0 /*installFlags*/,
13977                        PackageManager.INSTALL_REASON_DEVICE_SETUP);
13978                return true;
13979            }
13980
13981            // uninstall the app from installed state
13982            deletePackageVersioned(
13983                    new VersionedPackage(packageName, PackageManager.VERSION_CODE_HIGHEST),
13984                    new LegacyPackageDeleteObserver(null).getBinder(),
13985                    userId,
13986                    PackageManager.DELETE_SYSTEM_APP);
13987            return true;
13988        } finally {
13989            Binder.restoreCallingIdentity(callingId);
13990        }
13991    }
13992
13993    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13994            int userId) {
13995        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13996        info.removedPackage = packageName;
13997        info.installerPackageName = pkgSetting.installerPackageName;
13998        info.removedUsers = new int[] {userId};
13999        info.broadcastUsers = new int[] {userId};
14000        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14001        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14002    }
14003
14004    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended,
14005            PersistableBundle launcherExtras) {
14006        if (pkgList.length > 0) {
14007            Bundle extras = new Bundle(1);
14008            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14009            if (launcherExtras != null) {
14010                extras.putBundle(Intent.EXTRA_LAUNCHER_EXTRAS,
14011                        new Bundle(launcherExtras.deepCopy()));
14012            }
14013            sendPackageBroadcast(
14014                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14015                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14016                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14017                    new int[] {userId}, null);
14018        }
14019    }
14020
14021    /**
14022     * Returns true if application is not found or there was an error. Otherwise it returns
14023     * the hidden state of the package for the given user.
14024     */
14025    @Override
14026    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14027        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14028        final int callingUid = Binder.getCallingUid();
14029        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14030                true /* requireFullPermission */, false /* checkShell */,
14031                "getApplicationHidden for user " + userId);
14032        PackageSetting ps;
14033        long callingId = Binder.clearCallingIdentity();
14034        try {
14035            // writer
14036            synchronized (mPackages) {
14037                ps = mSettings.mPackages.get(packageName);
14038                if (ps == null) {
14039                    return true;
14040                }
14041                if (filterAppAccessLPr(ps, callingUid, userId)) {
14042                    return true;
14043                }
14044                return ps.getHidden(userId);
14045            }
14046        } finally {
14047            Binder.restoreCallingIdentity(callingId);
14048        }
14049    }
14050
14051    /**
14052     * @hide
14053     */
14054    @Override
14055    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14056            int installReason) {
14057        final int callingUid = Binder.getCallingUid();
14058        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES)
14059                != PackageManager.PERMISSION_GRANTED
14060                && mContext.checkCallingOrSelfPermission(
14061                        android.Manifest.permission.INSTALL_EXISTING_PACKAGES)
14062                != PackageManager.PERMISSION_GRANTED) {
14063            throw new SecurityException("Neither user " + callingUid + " nor current process has "
14064                    + android.Manifest.permission.INSTALL_PACKAGES + ".");
14065        }
14066        PackageSetting pkgSetting;
14067        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14068                true /* requireFullPermission */, true /* checkShell */,
14069                "installExistingPackage for user " + userId);
14070        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14071            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14072        }
14073
14074        long callingId = Binder.clearCallingIdentity();
14075        try {
14076            boolean installed = false;
14077            final boolean instantApp =
14078                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14079            final boolean fullApp =
14080                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14081
14082            // writer
14083            synchronized (mPackages) {
14084                pkgSetting = mSettings.mPackages.get(packageName);
14085                if (pkgSetting == null) {
14086                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14087                }
14088                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14089                    // only allow the existing package to be used if it's installed as a full
14090                    // application for at least one user
14091                    boolean installAllowed = false;
14092                    for (int checkUserId : sUserManager.getUserIds()) {
14093                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14094                        if (installAllowed) {
14095                            break;
14096                        }
14097                    }
14098                    if (!installAllowed) {
14099                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14100                    }
14101                }
14102                if (!pkgSetting.getInstalled(userId)) {
14103                    pkgSetting.setInstalled(true, userId);
14104                    pkgSetting.setHidden(false, userId);
14105                    pkgSetting.setInstallReason(installReason, userId);
14106                    mSettings.writePackageRestrictionsLPr(userId);
14107                    mSettings.writeKernelMappingLPr(pkgSetting);
14108                    installed = true;
14109                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14110                    // upgrade app from instant to full; we don't allow app downgrade
14111                    installed = true;
14112                }
14113                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14114            }
14115
14116            if (installed) {
14117                if (pkgSetting.pkg != null) {
14118                    synchronized (mInstallLock) {
14119                        // We don't need to freeze for a brand new install
14120                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14121                    }
14122                }
14123                sendPackageAddedForUser(packageName, pkgSetting, userId);
14124                synchronized (mPackages) {
14125                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14126                }
14127            }
14128        } finally {
14129            Binder.restoreCallingIdentity(callingId);
14130        }
14131
14132        return PackageManager.INSTALL_SUCCEEDED;
14133    }
14134
14135    static void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14136            boolean instantApp, boolean fullApp) {
14137        // no state specified; do nothing
14138        if (!instantApp && !fullApp) {
14139            return;
14140        }
14141        if (userId != UserHandle.USER_ALL) {
14142            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14143                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14144            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14145                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14146            }
14147        } else {
14148            for (int currentUserId : sUserManager.getUserIds()) {
14149                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14150                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14151                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14152                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14153                }
14154            }
14155        }
14156    }
14157
14158    boolean isUserRestricted(int userId, String restrictionKey) {
14159        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14160        if (restrictions.getBoolean(restrictionKey, false)) {
14161            Log.w(TAG, "User is restricted: " + restrictionKey);
14162            return true;
14163        }
14164        return false;
14165    }
14166
14167    @Override
14168    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14169            PersistableBundle appExtras, PersistableBundle launcherExtras, String dialogMessage,
14170            String callingPackage, int userId) {
14171        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.SUSPEND_APPS,
14172                "setPackagesSuspendedAsUser");
14173
14174        final int callingUid = Binder.getCallingUid();
14175        if (callingUid != Process.ROOT_UID && callingUid != Process.SYSTEM_UID
14176                && getPackageUid(callingPackage, 0, userId) != callingUid) {
14177            throw new SecurityException("Calling package " + callingPackage + " in user "
14178                    + userId + " does not belong to calling uid " + callingUid);
14179        }
14180        if (!PLATFORM_PACKAGE_NAME.equals(callingPackage)
14181                && mProtectedPackages.getDeviceOwnerOrProfileOwnerPackage(userId) != null) {
14182            throw new UnsupportedOperationException("Cannot suspend/unsuspend packages. User "
14183                    + userId + " has an active DO or PO");
14184        }
14185        if (ArrayUtils.isEmpty(packageNames)) {
14186            return packageNames;
14187        }
14188
14189        final List<String> changedPackagesList = new ArrayList<>(packageNames.length);
14190        final List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14191        final long callingId = Binder.clearCallingIdentity();
14192        try {
14193            synchronized (mPackages) {
14194                for (int i = 0; i < packageNames.length; i++) {
14195                    final String packageName = packageNames[i];
14196                    if (callingPackage.equals(packageName)) {
14197                        Slog.w(TAG, "Calling package: " + callingPackage + " trying to "
14198                                + (suspended ? "" : "un") + "suspend itself. Ignoring");
14199                        unactionedPackages.add(packageName);
14200                        continue;
14201                    }
14202                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14203                    if (pkgSetting == null
14204                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14205                        Slog.w(TAG, "Could not find package setting for package: " + packageName
14206                                + ". Skipping suspending/un-suspending.");
14207                        unactionedPackages.add(packageName);
14208                        continue;
14209                    }
14210                    if (!canSuspendPackageForUserLocked(packageName, userId)) {
14211                        unactionedPackages.add(packageName);
14212                        continue;
14213                    }
14214                    pkgSetting.setSuspended(suspended, callingPackage, dialogMessage, appExtras,
14215                            launcherExtras, userId);
14216                    changedPackagesList.add(packageName);
14217                }
14218            }
14219        } finally {
14220            Binder.restoreCallingIdentity(callingId);
14221        }
14222        if (!changedPackagesList.isEmpty()) {
14223            final String[] changedPackages = changedPackagesList.toArray(
14224                    new String[changedPackagesList.size()]);
14225            sendPackagesSuspendedForUser(changedPackages, userId, suspended, launcherExtras);
14226            sendMyPackageSuspendedOrUnsuspended(changedPackages, suspended, appExtras, userId);
14227            synchronized (mPackages) {
14228                scheduleWritePackageRestrictionsLocked(userId);
14229            }
14230        }
14231        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14232    }
14233
14234    @Override
14235    public PersistableBundle getSuspendedPackageAppExtras(String packageName, int userId) {
14236        final int callingUid = Binder.getCallingUid();
14237        if (getPackageUid(packageName, 0, userId) != callingUid) {
14238            throw new SecurityException("Calling package " + packageName
14239                    + " does not belong to calling uid " + callingUid);
14240        }
14241        synchronized (mPackages) {
14242            final PackageSetting ps = mSettings.mPackages.get(packageName);
14243            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14244                throw new IllegalArgumentException("Unknown target package: " + packageName);
14245            }
14246            final PackageUserState packageUserState = ps.readUserState(userId);
14247            if (packageUserState.suspended) {
14248                return packageUserState.suspendedAppExtras;
14249            }
14250            return null;
14251        }
14252    }
14253
14254    private void sendMyPackageSuspendedOrUnsuspended(String[] affectedPackages, boolean suspended,
14255            PersistableBundle appExtras, int userId) {
14256        final String action;
14257        final Bundle intentExtras = new Bundle();
14258        if (suspended) {
14259            action = Intent.ACTION_MY_PACKAGE_SUSPENDED;
14260            if (appExtras != null) {
14261                final Bundle bundledAppExtras = new Bundle(appExtras.deepCopy());
14262                intentExtras.putBundle(Intent.EXTRA_SUSPENDED_PACKAGE_EXTRAS, bundledAppExtras);
14263            }
14264        } else {
14265            action = Intent.ACTION_MY_PACKAGE_UNSUSPENDED;
14266        }
14267        mHandler.post(new Runnable() {
14268            @Override
14269            public void run() {
14270                try {
14271                    final IActivityManager am = ActivityManager.getService();
14272                    if (am == null) {
14273                        Slog.wtf(TAG, "IActivityManager null. Cannot send MY_PACKAGE_ "
14274                                + (suspended ? "" : "UN") + "SUSPENDED broadcasts");
14275                        return;
14276                    }
14277                    final int[] targetUserIds = new int[] {userId};
14278                    for (String packageName : affectedPackages) {
14279                        doSendBroadcast(am, action, null, intentExtras,
14280                                Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, packageName, null,
14281                                targetUserIds, false);
14282                    }
14283                } catch (RemoteException ex) {
14284                    // Shouldn't happen as AMS is in the same process.
14285                }
14286            }
14287        });
14288    }
14289
14290    @Override
14291    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14292        final int callingUid = Binder.getCallingUid();
14293        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14294                true /* requireFullPermission */, false /* checkShell */,
14295                "isPackageSuspendedForUser for user " + userId);
14296        synchronized (mPackages) {
14297            final PackageSetting ps = mSettings.mPackages.get(packageName);
14298            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14299                throw new IllegalArgumentException("Unknown target package: " + packageName);
14300            }
14301            return ps.getSuspended(userId);
14302        }
14303    }
14304
14305    /**
14306     * Immediately unsuspends any packages suspended by the given package. To be called
14307     * when such a package's data is cleared or it is removed from the device.
14308     *
14309     * <p><b>Should not be used on a frequent code path</b> as it flushes state to disk
14310     * synchronously
14311     *
14312     * @param packageName The package holding {@link Manifest.permission#SUSPEND_APPS} permission
14313     * @param affectedUser The user for which the changes are taking place.
14314     */
14315    void unsuspendForSuspendingPackage(final String packageName, int affectedUser) {
14316        final int[] userIds = (affectedUser == UserHandle.USER_ALL) ? sUserManager.getUserIds()
14317                : new int[] {affectedUser};
14318        for (int userId : userIds) {
14319            unsuspendForSuspendingPackages(packageName::equals, userId);
14320        }
14321    }
14322
14323    /**
14324     * Immediately unsuspends any packages in the given users not suspended by the platform or root.
14325     * To be called when a profile owner or a device owner is added.
14326     *
14327     * <p><b>Should not be used on a frequent code path</b> as it flushes state to disk
14328     * synchronously
14329     *
14330     * @param userIds The users for which to unsuspend packages
14331     */
14332    void unsuspendForNonSystemSuspendingPackages(ArraySet<Integer> userIds) {
14333        final int sz = userIds.size();
14334        for (int i = 0; i < sz; i++) {
14335            unsuspendForSuspendingPackages(
14336                    (suspendingPackage) -> !PLATFORM_PACKAGE_NAME.equals(suspendingPackage),
14337                    userIds.valueAt(i));
14338        }
14339    }
14340
14341    private void unsuspendForSuspendingPackages(Predicate<String> packagePredicate, int userId) {
14342        final List<String> affectedPackages = new ArrayList<>();
14343        synchronized (mPackages) {
14344            for (PackageSetting ps : mSettings.mPackages.values()) {
14345                final PackageUserState pus = ps.readUserState(userId);
14346                if (pus.suspended && packagePredicate.test(pus.suspendingPackage)) {
14347                    ps.setSuspended(false, null, null, null, null, userId);
14348                    affectedPackages.add(ps.name);
14349                }
14350            }
14351        }
14352        if (!affectedPackages.isEmpty()) {
14353            final String[] packageArray = affectedPackages.toArray(
14354                    new String[affectedPackages.size()]);
14355            sendMyPackageSuspendedOrUnsuspended(packageArray, false, null, userId);
14356            sendPackagesSuspendedForUser(packageArray, userId, false, null);
14357            // Write package restrictions immediately to avoid an inconsistent state.
14358            mSettings.writePackageRestrictionsLPr(userId);
14359        }
14360    }
14361
14362    @GuardedBy("mPackages")
14363    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14364        if (isPackageDeviceAdmin(packageName, userId)) {
14365            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14366                    + "\": has an active device admin");
14367            return false;
14368        }
14369
14370        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14371        if (packageName.equals(activeLauncherPackageName)) {
14372            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14373                    + "\": contains the active launcher");
14374            return false;
14375        }
14376
14377        if (packageName.equals(mRequiredInstallerPackage)) {
14378            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14379                    + "\": required for package installation");
14380            return false;
14381        }
14382
14383        if (packageName.equals(mRequiredUninstallerPackage)) {
14384            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14385                    + "\": required for package uninstallation");
14386            return false;
14387        }
14388
14389        if (packageName.equals(mRequiredVerifierPackage)) {
14390            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14391                    + "\": required for package verification");
14392            return false;
14393        }
14394
14395        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14396            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14397                    + "\": is the default dialer");
14398            return false;
14399        }
14400
14401        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14402            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14403                    + "\": protected package");
14404            return false;
14405        }
14406
14407        // Cannot suspend static shared libs as they are considered
14408        // a part of the using app (emulating static linking). Also
14409        // static libs are installed always on internal storage.
14410        PackageParser.Package pkg = mPackages.get(packageName);
14411        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14412            Slog.w(TAG, "Cannot suspend package: " + packageName
14413                    + " providing static shared library: "
14414                    + pkg.staticSharedLibName);
14415            return false;
14416        }
14417
14418        if (PLATFORM_PACKAGE_NAME.equals(packageName)) {
14419            Slog.w(TAG, "Cannot suspend package: " + packageName);
14420            return false;
14421        }
14422
14423        return true;
14424    }
14425
14426    private String getActiveLauncherPackageName(int userId) {
14427        Intent intent = new Intent(Intent.ACTION_MAIN);
14428        intent.addCategory(Intent.CATEGORY_HOME);
14429        ResolveInfo resolveInfo = resolveIntent(
14430                intent,
14431                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14432                PackageManager.MATCH_DEFAULT_ONLY,
14433                userId);
14434
14435        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14436    }
14437
14438    private String getDefaultDialerPackageName(int userId) {
14439        synchronized (mPackages) {
14440            return mSettings.getDefaultDialerPackageNameLPw(userId);
14441        }
14442    }
14443
14444    @Override
14445    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14446        mContext.enforceCallingOrSelfPermission(
14447                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14448                "Only package verification agents can verify applications");
14449
14450        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14451        final PackageVerificationResponse response = new PackageVerificationResponse(
14452                verificationCode, Binder.getCallingUid());
14453        msg.arg1 = id;
14454        msg.obj = response;
14455        mHandler.sendMessage(msg);
14456    }
14457
14458    @Override
14459    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14460            long millisecondsToDelay) {
14461        mContext.enforceCallingOrSelfPermission(
14462                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14463                "Only package verification agents can extend verification timeouts");
14464
14465        final PackageVerificationState state = mPendingVerification.get(id);
14466        final PackageVerificationResponse response = new PackageVerificationResponse(
14467                verificationCodeAtTimeout, Binder.getCallingUid());
14468
14469        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14470            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14471        }
14472        if (millisecondsToDelay < 0) {
14473            millisecondsToDelay = 0;
14474        }
14475        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14476                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14477            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14478        }
14479
14480        if ((state != null) && !state.timeoutExtended()) {
14481            state.extendTimeout();
14482
14483            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14484            msg.arg1 = id;
14485            msg.obj = response;
14486            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14487        }
14488    }
14489
14490    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14491            int verificationCode, UserHandle user) {
14492        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14493        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14494        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14495        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14496        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14497
14498        mContext.sendBroadcastAsUser(intent, user,
14499                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14500    }
14501
14502    private ComponentName matchComponentForVerifier(String packageName,
14503            List<ResolveInfo> receivers) {
14504        ActivityInfo targetReceiver = null;
14505
14506        final int NR = receivers.size();
14507        for (int i = 0; i < NR; i++) {
14508            final ResolveInfo info = receivers.get(i);
14509            if (info.activityInfo == null) {
14510                continue;
14511            }
14512
14513            if (packageName.equals(info.activityInfo.packageName)) {
14514                targetReceiver = info.activityInfo;
14515                break;
14516            }
14517        }
14518
14519        if (targetReceiver == null) {
14520            return null;
14521        }
14522
14523        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14524    }
14525
14526    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14527            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14528        if (pkgInfo.verifiers.length == 0) {
14529            return null;
14530        }
14531
14532        final int N = pkgInfo.verifiers.length;
14533        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14534        for (int i = 0; i < N; i++) {
14535            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14536
14537            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14538                    receivers);
14539            if (comp == null) {
14540                continue;
14541            }
14542
14543            final int verifierUid = getUidForVerifier(verifierInfo);
14544            if (verifierUid == -1) {
14545                continue;
14546            }
14547
14548            if (DEBUG_VERIFY) {
14549                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14550                        + " with the correct signature");
14551            }
14552            sufficientVerifiers.add(comp);
14553            verificationState.addSufficientVerifier(verifierUid);
14554        }
14555
14556        return sufficientVerifiers;
14557    }
14558
14559    private int getUidForVerifier(VerifierInfo verifierInfo) {
14560        synchronized (mPackages) {
14561            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14562            if (pkg == null) {
14563                return -1;
14564            } else if (pkg.mSigningDetails.signatures.length != 1) {
14565                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14566                        + " has more than one signature; ignoring");
14567                return -1;
14568            }
14569
14570            /*
14571             * If the public key of the package's signature does not match
14572             * our expected public key, then this is a different package and
14573             * we should skip.
14574             */
14575
14576            final byte[] expectedPublicKey;
14577            try {
14578                final Signature verifierSig = pkg.mSigningDetails.signatures[0];
14579                final PublicKey publicKey = verifierSig.getPublicKey();
14580                expectedPublicKey = publicKey.getEncoded();
14581            } catch (CertificateException e) {
14582                return -1;
14583            }
14584
14585            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14586
14587            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14588                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14589                        + " does not have the expected public key; ignoring");
14590                return -1;
14591            }
14592
14593            return pkg.applicationInfo.uid;
14594        }
14595    }
14596
14597    @Override
14598    public void finishPackageInstall(int token, boolean didLaunch) {
14599        enforceSystemOrRoot("Only the system is allowed to finish installs");
14600
14601        if (DEBUG_INSTALL) {
14602            Slog.v(TAG, "BM finishing package install for " + token);
14603        }
14604        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14605
14606        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14607        mHandler.sendMessage(msg);
14608    }
14609
14610    /**
14611     * Get the verification agent timeout.  Used for both the APK verifier and the
14612     * intent filter verifier.
14613     *
14614     * @return verification timeout in milliseconds
14615     */
14616    private long getVerificationTimeout() {
14617        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14618                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14619                DEFAULT_VERIFICATION_TIMEOUT);
14620    }
14621
14622    /**
14623     * Get the default verification agent response code.
14624     *
14625     * @return default verification response code
14626     */
14627    private int getDefaultVerificationResponse(UserHandle user) {
14628        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14629            return PackageManager.VERIFICATION_REJECT;
14630        }
14631        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14632                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14633                DEFAULT_VERIFICATION_RESPONSE);
14634    }
14635
14636    /**
14637     * Check whether or not package verification has been enabled.
14638     *
14639     * @return true if verification should be performed
14640     */
14641    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14642        if (!DEFAULT_VERIFY_ENABLE) {
14643            return false;
14644        }
14645
14646        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14647
14648        // Check if installing from ADB
14649        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14650            // Do not run verification in a test harness environment
14651            if (ActivityManager.isRunningInTestHarness()) {
14652                return false;
14653            }
14654            if (ensureVerifyAppsEnabled) {
14655                return true;
14656            }
14657            // Check if the developer does not want package verification for ADB installs
14658            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14659                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14660                return false;
14661            }
14662        } else {
14663            // only when not installed from ADB, skip verification for instant apps when
14664            // the installer and verifier are the same.
14665            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14666                if (mInstantAppInstallerActivity != null
14667                        && mInstantAppInstallerActivity.packageName.equals(
14668                                mRequiredVerifierPackage)) {
14669                    try {
14670                        mContext.getSystemService(AppOpsManager.class)
14671                                .checkPackage(installerUid, mRequiredVerifierPackage);
14672                        if (DEBUG_VERIFY) {
14673                            Slog.i(TAG, "disable verification for instant app");
14674                        }
14675                        return false;
14676                    } catch (SecurityException ignore) { }
14677                }
14678            }
14679        }
14680
14681        if (ensureVerifyAppsEnabled) {
14682            return true;
14683        }
14684
14685        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14686                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14687    }
14688
14689    @Override
14690    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14691            throws RemoteException {
14692        mContext.enforceCallingOrSelfPermission(
14693                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14694                "Only intentfilter verification agents can verify applications");
14695
14696        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14697        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14698                Binder.getCallingUid(), verificationCode, failedDomains);
14699        msg.arg1 = id;
14700        msg.obj = response;
14701        mHandler.sendMessage(msg);
14702    }
14703
14704    @Override
14705    public int getIntentVerificationStatus(String packageName, int userId) {
14706        final int callingUid = Binder.getCallingUid();
14707        if (UserHandle.getUserId(callingUid) != userId) {
14708            mContext.enforceCallingOrSelfPermission(
14709                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14710                    "getIntentVerificationStatus" + userId);
14711        }
14712        if (getInstantAppPackageName(callingUid) != null) {
14713            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14714        }
14715        synchronized (mPackages) {
14716            final PackageSetting ps = mSettings.mPackages.get(packageName);
14717            if (ps == null
14718                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14719                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14720            }
14721            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14722        }
14723    }
14724
14725    @Override
14726    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14727        mContext.enforceCallingOrSelfPermission(
14728                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14729
14730        boolean result = false;
14731        synchronized (mPackages) {
14732            final PackageSetting ps = mSettings.mPackages.get(packageName);
14733            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14734                return false;
14735            }
14736            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14737        }
14738        if (result) {
14739            scheduleWritePackageRestrictionsLocked(userId);
14740        }
14741        return result;
14742    }
14743
14744    @Override
14745    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14746            String packageName) {
14747        final int callingUid = Binder.getCallingUid();
14748        if (getInstantAppPackageName(callingUid) != null) {
14749            return ParceledListSlice.emptyList();
14750        }
14751        synchronized (mPackages) {
14752            final PackageSetting ps = mSettings.mPackages.get(packageName);
14753            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14754                return ParceledListSlice.emptyList();
14755            }
14756            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14757        }
14758    }
14759
14760    @Override
14761    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14762        if (TextUtils.isEmpty(packageName)) {
14763            return ParceledListSlice.emptyList();
14764        }
14765        final int callingUid = Binder.getCallingUid();
14766        final int callingUserId = UserHandle.getUserId(callingUid);
14767        synchronized (mPackages) {
14768            PackageParser.Package pkg = mPackages.get(packageName);
14769            if (pkg == null || pkg.activities == null) {
14770                return ParceledListSlice.emptyList();
14771            }
14772            if (pkg.mExtras == null) {
14773                return ParceledListSlice.emptyList();
14774            }
14775            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14776            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14777                return ParceledListSlice.emptyList();
14778            }
14779            final int count = pkg.activities.size();
14780            ArrayList<IntentFilter> result = new ArrayList<>();
14781            for (int n=0; n<count; n++) {
14782                PackageParser.Activity activity = pkg.activities.get(n);
14783                if (activity.intents != null && activity.intents.size() > 0) {
14784                    result.addAll(activity.intents);
14785                }
14786            }
14787            return new ParceledListSlice<>(result);
14788        }
14789    }
14790
14791    @Override
14792    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14793        mContext.enforceCallingOrSelfPermission(
14794                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14795        if (UserHandle.getCallingUserId() != userId) {
14796            mContext.enforceCallingOrSelfPermission(
14797                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14798        }
14799
14800        synchronized (mPackages) {
14801            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14802            if (packageName != null) {
14803                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14804                        packageName, userId);
14805            }
14806            return result;
14807        }
14808    }
14809
14810    @Override
14811    public String getDefaultBrowserPackageName(int userId) {
14812        if (UserHandle.getCallingUserId() != userId) {
14813            mContext.enforceCallingOrSelfPermission(
14814                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14815        }
14816        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14817            return null;
14818        }
14819        synchronized (mPackages) {
14820            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14821        }
14822    }
14823
14824    /**
14825     * Get the "allow unknown sources" setting.
14826     *
14827     * @return the current "allow unknown sources" setting
14828     */
14829    private int getUnknownSourcesSettings() {
14830        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14831                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14832                -1);
14833    }
14834
14835    @Override
14836    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14837        final int callingUid = Binder.getCallingUid();
14838        if (getInstantAppPackageName(callingUid) != null) {
14839            return;
14840        }
14841        // writer
14842        synchronized (mPackages) {
14843            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14844            if (targetPackageSetting == null
14845                    || filterAppAccessLPr(
14846                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14847                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14848            }
14849
14850            PackageSetting installerPackageSetting;
14851            if (installerPackageName != null) {
14852                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14853                if (installerPackageSetting == null) {
14854                    throw new IllegalArgumentException("Unknown installer package: "
14855                            + installerPackageName);
14856                }
14857            } else {
14858                installerPackageSetting = null;
14859            }
14860
14861            Signature[] callerSignature;
14862            Object obj = mSettings.getUserIdLPr(callingUid);
14863            if (obj != null) {
14864                if (obj instanceof SharedUserSetting) {
14865                    callerSignature =
14866                            ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
14867                } else if (obj instanceof PackageSetting) {
14868                    callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
14869                } else {
14870                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14871                }
14872            } else {
14873                throw new SecurityException("Unknown calling UID: " + callingUid);
14874            }
14875
14876            // Verify: can't set installerPackageName to a package that is
14877            // not signed with the same cert as the caller.
14878            if (installerPackageSetting != null) {
14879                if (compareSignatures(callerSignature,
14880                        installerPackageSetting.signatures.mSigningDetails.signatures)
14881                        != PackageManager.SIGNATURE_MATCH) {
14882                    throw new SecurityException(
14883                            "Caller does not have same cert as new installer package "
14884                            + installerPackageName);
14885                }
14886            }
14887
14888            // Verify: if target already has an installer package, it must
14889            // be signed with the same cert as the caller.
14890            if (targetPackageSetting.installerPackageName != null) {
14891                PackageSetting setting = mSettings.mPackages.get(
14892                        targetPackageSetting.installerPackageName);
14893                // If the currently set package isn't valid, then it's always
14894                // okay to change it.
14895                if (setting != null) {
14896                    if (compareSignatures(callerSignature,
14897                            setting.signatures.mSigningDetails.signatures)
14898                            != PackageManager.SIGNATURE_MATCH) {
14899                        throw new SecurityException(
14900                                "Caller does not have same cert as old installer package "
14901                                + targetPackageSetting.installerPackageName);
14902                    }
14903                }
14904            }
14905
14906            // Okay!
14907            targetPackageSetting.installerPackageName = installerPackageName;
14908            if (installerPackageName != null) {
14909                mSettings.mInstallerPackages.add(installerPackageName);
14910            }
14911            scheduleWriteSettingsLocked();
14912        }
14913    }
14914
14915    @Override
14916    public void setApplicationCategoryHint(String packageName, int categoryHint,
14917            String callerPackageName) {
14918        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14919            throw new SecurityException("Instant applications don't have access to this method");
14920        }
14921        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14922                callerPackageName);
14923        synchronized (mPackages) {
14924            PackageSetting ps = mSettings.mPackages.get(packageName);
14925            if (ps == null) {
14926                throw new IllegalArgumentException("Unknown target package " + packageName);
14927            }
14928            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14929                throw new IllegalArgumentException("Unknown target package " + packageName);
14930            }
14931            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14932                throw new IllegalArgumentException("Calling package " + callerPackageName
14933                        + " is not installer for " + packageName);
14934            }
14935
14936            if (ps.categoryHint != categoryHint) {
14937                ps.categoryHint = categoryHint;
14938                scheduleWriteSettingsLocked();
14939            }
14940        }
14941    }
14942
14943    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14944        // Queue up an async operation since the package installation may take a little while.
14945        mHandler.post(new Runnable() {
14946            public void run() {
14947                mHandler.removeCallbacks(this);
14948                 // Result object to be returned
14949                PackageInstalledInfo res = new PackageInstalledInfo();
14950                res.setReturnCode(currentStatus);
14951                res.uid = -1;
14952                res.pkg = null;
14953                res.removedInfo = null;
14954                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14955                    args.doPreInstall(res.returnCode);
14956                    synchronized (mInstallLock) {
14957                        installPackageTracedLI(args, res);
14958                    }
14959                    args.doPostInstall(res.returnCode, res.uid);
14960                }
14961
14962                // A restore should be performed at this point if (a) the install
14963                // succeeded, (b) the operation is not an update, and (c) the new
14964                // package has not opted out of backup participation.
14965                final boolean update = res.removedInfo != null
14966                        && res.removedInfo.removedPackage != null;
14967                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14968                boolean doRestore = !update
14969                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14970
14971                // Set up the post-install work request bookkeeping.  This will be used
14972                // and cleaned up by the post-install event handling regardless of whether
14973                // there's a restore pass performed.  Token values are >= 1.
14974                int token;
14975                if (mNextInstallToken < 0) mNextInstallToken = 1;
14976                token = mNextInstallToken++;
14977
14978                PostInstallData data = new PostInstallData(args, res);
14979                mRunningInstalls.put(token, data);
14980                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14981
14982                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14983                    // Pass responsibility to the Backup Manager.  It will perform a
14984                    // restore if appropriate, then pass responsibility back to the
14985                    // Package Manager to run the post-install observer callbacks
14986                    // and broadcasts.
14987                    IBackupManager bm = IBackupManager.Stub.asInterface(
14988                            ServiceManager.getService(Context.BACKUP_SERVICE));
14989                    if (bm != null) {
14990                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14991                                + " to BM for possible restore");
14992                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14993                        try {
14994                            // TODO: http://b/22388012
14995                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14996                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14997                            } else {
14998                                doRestore = false;
14999                            }
15000                        } catch (RemoteException e) {
15001                            // can't happen; the backup manager is local
15002                        } catch (Exception e) {
15003                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15004                            doRestore = false;
15005                        }
15006                    } else {
15007                        Slog.e(TAG, "Backup Manager not found!");
15008                        doRestore = false;
15009                    }
15010                }
15011
15012                if (!doRestore) {
15013                    // No restore possible, or the Backup Manager was mysteriously not
15014                    // available -- just fire the post-install work request directly.
15015                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15016
15017                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15018
15019                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15020                    mHandler.sendMessage(msg);
15021                }
15022            }
15023        });
15024    }
15025
15026    /**
15027     * Callback from PackageSettings whenever an app is first transitioned out of the
15028     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15029     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15030     * here whether the app is the target of an ongoing install, and only send the
15031     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15032     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15033     * handling.
15034     */
15035    void notifyFirstLaunch(final String packageName, final String installerPackage,
15036            final int userId) {
15037        // Serialize this with the rest of the install-process message chain.  In the
15038        // restore-at-install case, this Runnable will necessarily run before the
15039        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15040        // are coherent.  In the non-restore case, the app has already completed install
15041        // and been launched through some other means, so it is not in a problematic
15042        // state for observers to see the FIRST_LAUNCH signal.
15043        mHandler.post(new Runnable() {
15044            @Override
15045            public void run() {
15046                for (int i = 0; i < mRunningInstalls.size(); i++) {
15047                    final PostInstallData data = mRunningInstalls.valueAt(i);
15048                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15049                        continue;
15050                    }
15051                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
15052                        // right package; but is it for the right user?
15053                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15054                            if (userId == data.res.newUsers[uIndex]) {
15055                                if (DEBUG_BACKUP) {
15056                                    Slog.i(TAG, "Package " + packageName
15057                                            + " being restored so deferring FIRST_LAUNCH");
15058                                }
15059                                return;
15060                            }
15061                        }
15062                    }
15063                }
15064                // didn't find it, so not being restored
15065                if (DEBUG_BACKUP) {
15066                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
15067                }
15068                final boolean isInstantApp = isInstantApp(packageName, userId);
15069                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
15070                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
15071                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
15072            }
15073        });
15074    }
15075
15076    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
15077            int[] userIds, int[] instantUserIds) {
15078        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15079                installerPkg, null, userIds, instantUserIds);
15080    }
15081
15082    private abstract class HandlerParams {
15083        private static final int MAX_RETRIES = 4;
15084
15085        /**
15086         * Number of times startCopy() has been attempted and had a non-fatal
15087         * error.
15088         */
15089        private int mRetries = 0;
15090
15091        /** User handle for the user requesting the information or installation. */
15092        private final UserHandle mUser;
15093        String traceMethod;
15094        int traceCookie;
15095
15096        HandlerParams(UserHandle user) {
15097            mUser = user;
15098        }
15099
15100        UserHandle getUser() {
15101            return mUser;
15102        }
15103
15104        HandlerParams setTraceMethod(String traceMethod) {
15105            this.traceMethod = traceMethod;
15106            return this;
15107        }
15108
15109        HandlerParams setTraceCookie(int traceCookie) {
15110            this.traceCookie = traceCookie;
15111            return this;
15112        }
15113
15114        final boolean startCopy() {
15115            boolean res;
15116            try {
15117                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15118
15119                if (++mRetries > MAX_RETRIES) {
15120                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15121                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15122                    handleServiceError();
15123                    return false;
15124                } else {
15125                    handleStartCopy();
15126                    res = true;
15127                }
15128            } catch (RemoteException e) {
15129                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15130                mHandler.sendEmptyMessage(MCS_RECONNECT);
15131                res = false;
15132            }
15133            handleReturnCode();
15134            return res;
15135        }
15136
15137        final void serviceError() {
15138            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15139            handleServiceError();
15140            handleReturnCode();
15141        }
15142
15143        abstract void handleStartCopy() throws RemoteException;
15144        abstract void handleServiceError();
15145        abstract void handleReturnCode();
15146    }
15147
15148    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15149        for (File path : paths) {
15150            try {
15151                mcs.clearDirectory(path.getAbsolutePath());
15152            } catch (RemoteException e) {
15153            }
15154        }
15155    }
15156
15157    static class OriginInfo {
15158        /**
15159         * Location where install is coming from, before it has been
15160         * copied/renamed into place. This could be a single monolithic APK
15161         * file, or a cluster directory. This location may be untrusted.
15162         */
15163        final File file;
15164
15165        /**
15166         * Flag indicating that {@link #file} or {@link #cid} has already been
15167         * staged, meaning downstream users don't need to defensively copy the
15168         * contents.
15169         */
15170        final boolean staged;
15171
15172        /**
15173         * Flag indicating that {@link #file} or {@link #cid} is an already
15174         * installed app that is being moved.
15175         */
15176        final boolean existing;
15177
15178        final String resolvedPath;
15179        final File resolvedFile;
15180
15181        static OriginInfo fromNothing() {
15182            return new OriginInfo(null, false, false);
15183        }
15184
15185        static OriginInfo fromUntrustedFile(File file) {
15186            return new OriginInfo(file, false, false);
15187        }
15188
15189        static OriginInfo fromExistingFile(File file) {
15190            return new OriginInfo(file, false, true);
15191        }
15192
15193        static OriginInfo fromStagedFile(File file) {
15194            return new OriginInfo(file, true, false);
15195        }
15196
15197        private OriginInfo(File file, boolean staged, boolean existing) {
15198            this.file = file;
15199            this.staged = staged;
15200            this.existing = existing;
15201
15202            if (file != null) {
15203                resolvedPath = file.getAbsolutePath();
15204                resolvedFile = file;
15205            } else {
15206                resolvedPath = null;
15207                resolvedFile = null;
15208            }
15209        }
15210    }
15211
15212    static class MoveInfo {
15213        final int moveId;
15214        final String fromUuid;
15215        final String toUuid;
15216        final String packageName;
15217        final String dataAppName;
15218        final int appId;
15219        final String seinfo;
15220        final int targetSdkVersion;
15221
15222        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15223                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15224            this.moveId = moveId;
15225            this.fromUuid = fromUuid;
15226            this.toUuid = toUuid;
15227            this.packageName = packageName;
15228            this.dataAppName = dataAppName;
15229            this.appId = appId;
15230            this.seinfo = seinfo;
15231            this.targetSdkVersion = targetSdkVersion;
15232        }
15233    }
15234
15235    static class VerificationInfo {
15236        /** A constant used to indicate that a uid value is not present. */
15237        public static final int NO_UID = -1;
15238
15239        /** URI referencing where the package was downloaded from. */
15240        final Uri originatingUri;
15241
15242        /** HTTP referrer URI associated with the originatingURI. */
15243        final Uri referrer;
15244
15245        /** UID of the application that the install request originated from. */
15246        final int originatingUid;
15247
15248        /** UID of application requesting the install */
15249        final int installerUid;
15250
15251        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15252            this.originatingUri = originatingUri;
15253            this.referrer = referrer;
15254            this.originatingUid = originatingUid;
15255            this.installerUid = installerUid;
15256        }
15257    }
15258
15259    class InstallParams extends HandlerParams {
15260        final OriginInfo origin;
15261        final MoveInfo move;
15262        final IPackageInstallObserver2 observer;
15263        int installFlags;
15264        final String installerPackageName;
15265        final String volumeUuid;
15266        private InstallArgs mArgs;
15267        private int mRet;
15268        final String packageAbiOverride;
15269        final String[] grantedRuntimePermissions;
15270        final VerificationInfo verificationInfo;
15271        final PackageParser.SigningDetails signingDetails;
15272        final int installReason;
15273
15274        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15275                int installFlags, String installerPackageName, String volumeUuid,
15276                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15277                String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
15278            super(user);
15279            this.origin = origin;
15280            this.move = move;
15281            this.observer = observer;
15282            this.installFlags = installFlags;
15283            this.installerPackageName = installerPackageName;
15284            this.volumeUuid = volumeUuid;
15285            this.verificationInfo = verificationInfo;
15286            this.packageAbiOverride = packageAbiOverride;
15287            this.grantedRuntimePermissions = grantedPermissions;
15288            this.signingDetails = signingDetails;
15289            this.installReason = installReason;
15290        }
15291
15292        @Override
15293        public String toString() {
15294            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15295                    + " file=" + origin.file + "}";
15296        }
15297
15298        private int installLocationPolicy(PackageInfoLite pkgLite) {
15299            String packageName = pkgLite.packageName;
15300            int installLocation = pkgLite.installLocation;
15301            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15302            // reader
15303            synchronized (mPackages) {
15304                // Currently installed package which the new package is attempting to replace or
15305                // null if no such package is installed.
15306                PackageParser.Package installedPkg = mPackages.get(packageName);
15307                // Package which currently owns the data which the new package will own if installed.
15308                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15309                // will be null whereas dataOwnerPkg will contain information about the package
15310                // which was uninstalled while keeping its data.
15311                PackageParser.Package dataOwnerPkg = installedPkg;
15312                if (dataOwnerPkg  == null) {
15313                    PackageSetting ps = mSettings.mPackages.get(packageName);
15314                    if (ps != null) {
15315                        dataOwnerPkg = ps.pkg;
15316                    }
15317                }
15318
15319                if (dataOwnerPkg != null) {
15320                    // If installed, the package will get access to data left on the device by its
15321                    // predecessor. As a security measure, this is permited only if this is not a
15322                    // version downgrade or if the predecessor package is marked as debuggable and
15323                    // a downgrade is explicitly requested.
15324                    //
15325                    // On debuggable platform builds, downgrades are permitted even for
15326                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15327                    // not offer security guarantees and thus it's OK to disable some security
15328                    // mechanisms to make debugging/testing easier on those builds. However, even on
15329                    // debuggable builds downgrades of packages are permitted only if requested via
15330                    // installFlags. This is because we aim to keep the behavior of debuggable
15331                    // platform builds as close as possible to the behavior of non-debuggable
15332                    // platform builds.
15333                    final boolean downgradeRequested =
15334                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15335                    final boolean packageDebuggable =
15336                                (dataOwnerPkg.applicationInfo.flags
15337                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15338                    final boolean downgradePermitted =
15339                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15340                    if (!downgradePermitted) {
15341                        try {
15342                            checkDowngrade(dataOwnerPkg, pkgLite);
15343                        } catch (PackageManagerException e) {
15344                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15345                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15346                        }
15347                    }
15348                }
15349
15350                if (installedPkg != null) {
15351                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15352                        // Check for updated system application.
15353                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15354                            if (onSd) {
15355                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15356                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15357                            }
15358                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15359                        } else {
15360                            if (onSd) {
15361                                // Install flag overrides everything.
15362                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15363                            }
15364                            // If current upgrade specifies particular preference
15365                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15366                                // Application explicitly specified internal.
15367                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15368                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15369                                // App explictly prefers external. Let policy decide
15370                            } else {
15371                                // Prefer previous location
15372                                if (isExternal(installedPkg)) {
15373                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15374                                }
15375                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15376                            }
15377                        }
15378                    } else {
15379                        // Invalid install. Return error code
15380                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15381                    }
15382                }
15383            }
15384            // All the special cases have been taken care of.
15385            // Return result based on recommended install location.
15386            if (onSd) {
15387                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15388            }
15389            return pkgLite.recommendedInstallLocation;
15390        }
15391
15392        /*
15393         * Invoke remote method to get package information and install
15394         * location values. Override install location based on default
15395         * policy if needed and then create install arguments based
15396         * on the install location.
15397         */
15398        public void handleStartCopy() throws RemoteException {
15399            int ret = PackageManager.INSTALL_SUCCEEDED;
15400
15401            // If we're already staged, we've firmly committed to an install location
15402            if (origin.staged) {
15403                if (origin.file != null) {
15404                    installFlags |= PackageManager.INSTALL_INTERNAL;
15405                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15406                } else {
15407                    throw new IllegalStateException("Invalid stage location");
15408                }
15409            }
15410
15411            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15412            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15413            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15414            PackageInfoLite pkgLite = null;
15415
15416            if (onInt && onSd) {
15417                // Check if both bits are set.
15418                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15419                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15420            } else if (onSd && ephemeral) {
15421                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15422                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15423            } else {
15424                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15425                        packageAbiOverride);
15426
15427                if (DEBUG_INSTANT && ephemeral) {
15428                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15429                }
15430
15431                /*
15432                 * If we have too little free space, try to free cache
15433                 * before giving up.
15434                 */
15435                if (!origin.staged && pkgLite.recommendedInstallLocation
15436                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15437                    // TODO: focus freeing disk space on the target device
15438                    final StorageManager storage = StorageManager.from(mContext);
15439                    final long lowThreshold = storage.getStorageLowBytes(
15440                            Environment.getDataDirectory());
15441
15442                    final long sizeBytes = mContainerService.calculateInstalledSize(
15443                            origin.resolvedPath, packageAbiOverride);
15444
15445                    try {
15446                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15447                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15448                                installFlags, packageAbiOverride);
15449                    } catch (InstallerException e) {
15450                        Slog.w(TAG, "Failed to free cache", e);
15451                    }
15452
15453                    /*
15454                     * The cache free must have deleted the file we
15455                     * downloaded to install.
15456                     *
15457                     * TODO: fix the "freeCache" call to not delete
15458                     *       the file we care about.
15459                     */
15460                    if (pkgLite.recommendedInstallLocation
15461                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15462                        pkgLite.recommendedInstallLocation
15463                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15464                    }
15465                }
15466            }
15467
15468            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15469                int loc = pkgLite.recommendedInstallLocation;
15470                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15471                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15472                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15473                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15474                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15475                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15476                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15477                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15478                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15479                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15480                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15481                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15482                } else {
15483                    // Override with defaults if needed.
15484                    loc = installLocationPolicy(pkgLite);
15485                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15486                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15487                    } else if (!onSd && !onInt) {
15488                        // Override install location with flags
15489                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15490                            // Set the flag to install on external media.
15491                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15492                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15493                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15494                            if (DEBUG_INSTANT) {
15495                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15496                            }
15497                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15498                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15499                                    |PackageManager.INSTALL_INTERNAL);
15500                        } else {
15501                            // Make sure the flag for installing on external
15502                            // media is unset
15503                            installFlags |= PackageManager.INSTALL_INTERNAL;
15504                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15505                        }
15506                    }
15507                }
15508            }
15509
15510            final InstallArgs args = createInstallArgs(this);
15511            mArgs = args;
15512
15513            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15514                // TODO: http://b/22976637
15515                // Apps installed for "all" users use the device owner to verify the app
15516                UserHandle verifierUser = getUser();
15517                if (verifierUser == UserHandle.ALL) {
15518                    verifierUser = UserHandle.SYSTEM;
15519                }
15520
15521                /*
15522                 * Determine if we have any installed package verifiers. If we
15523                 * do, then we'll defer to them to verify the packages.
15524                 */
15525                final int requiredUid = mRequiredVerifierPackage == null ? -1
15526                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15527                                verifierUser.getIdentifier());
15528                final int installerUid =
15529                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15530                if (!origin.existing && requiredUid != -1
15531                        && isVerificationEnabled(
15532                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15533                    final Intent verification = new Intent(
15534                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15535                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15536                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15537                            PACKAGE_MIME_TYPE);
15538                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15539
15540                    // Query all live verifiers based on current user state
15541                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15542                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15543                            false /*allowDynamicSplits*/);
15544
15545                    if (DEBUG_VERIFY) {
15546                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15547                                + verification.toString() + " with " + pkgLite.verifiers.length
15548                                + " optional verifiers");
15549                    }
15550
15551                    final int verificationId = mPendingVerificationToken++;
15552
15553                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15554
15555                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15556                            installerPackageName);
15557
15558                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15559                            installFlags);
15560
15561                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15562                            pkgLite.packageName);
15563
15564                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15565                            pkgLite.versionCode);
15566
15567                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
15568                            pkgLite.getLongVersionCode());
15569
15570                    if (verificationInfo != null) {
15571                        if (verificationInfo.originatingUri != null) {
15572                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15573                                    verificationInfo.originatingUri);
15574                        }
15575                        if (verificationInfo.referrer != null) {
15576                            verification.putExtra(Intent.EXTRA_REFERRER,
15577                                    verificationInfo.referrer);
15578                        }
15579                        if (verificationInfo.originatingUid >= 0) {
15580                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15581                                    verificationInfo.originatingUid);
15582                        }
15583                        if (verificationInfo.installerUid >= 0) {
15584                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15585                                    verificationInfo.installerUid);
15586                        }
15587                    }
15588
15589                    final PackageVerificationState verificationState = new PackageVerificationState(
15590                            requiredUid, args);
15591
15592                    mPendingVerification.append(verificationId, verificationState);
15593
15594                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15595                            receivers, verificationState);
15596
15597                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15598                    final long idleDuration = getVerificationTimeout();
15599
15600                    /*
15601                     * If any sufficient verifiers were listed in the package
15602                     * manifest, attempt to ask them.
15603                     */
15604                    if (sufficientVerifiers != null) {
15605                        final int N = sufficientVerifiers.size();
15606                        if (N == 0) {
15607                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15608                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15609                        } else {
15610                            for (int i = 0; i < N; i++) {
15611                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15612                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15613                                        verifierComponent.getPackageName(), idleDuration,
15614                                        verifierUser.getIdentifier(), false, "package verifier");
15615
15616                                final Intent sufficientIntent = new Intent(verification);
15617                                sufficientIntent.setComponent(verifierComponent);
15618                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15619                            }
15620                        }
15621                    }
15622
15623                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15624                            mRequiredVerifierPackage, receivers);
15625                    if (ret == PackageManager.INSTALL_SUCCEEDED
15626                            && mRequiredVerifierPackage != null) {
15627                        Trace.asyncTraceBegin(
15628                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15629                        /*
15630                         * Send the intent to the required verification agent,
15631                         * but only start the verification timeout after the
15632                         * target BroadcastReceivers have run.
15633                         */
15634                        verification.setComponent(requiredVerifierComponent);
15635                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15636                                mRequiredVerifierPackage, idleDuration,
15637                                verifierUser.getIdentifier(), false, "package verifier");
15638                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15639                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15640                                new BroadcastReceiver() {
15641                                    @Override
15642                                    public void onReceive(Context context, Intent intent) {
15643                                        final Message msg = mHandler
15644                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15645                                        msg.arg1 = verificationId;
15646                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15647                                    }
15648                                }, null, 0, null, null);
15649
15650                        /*
15651                         * We don't want the copy to proceed until verification
15652                         * succeeds, so null out this field.
15653                         */
15654                        mArgs = null;
15655                    }
15656                } else {
15657                    /*
15658                     * No package verification is enabled, so immediately start
15659                     * the remote call to initiate copy using temporary file.
15660                     */
15661                    ret = args.copyApk(mContainerService, true);
15662                }
15663            }
15664
15665            mRet = ret;
15666        }
15667
15668        @Override
15669        void handleReturnCode() {
15670            // If mArgs is null, then MCS couldn't be reached. When it
15671            // reconnects, it will try again to install. At that point, this
15672            // will succeed.
15673            if (mArgs != null) {
15674                processPendingInstall(mArgs, mRet);
15675            }
15676        }
15677
15678        @Override
15679        void handleServiceError() {
15680            mArgs = createInstallArgs(this);
15681            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15682        }
15683    }
15684
15685    private InstallArgs createInstallArgs(InstallParams params) {
15686        if (params.move != null) {
15687            return new MoveInstallArgs(params);
15688        } else {
15689            return new FileInstallArgs(params);
15690        }
15691    }
15692
15693    /**
15694     * Create args that describe an existing installed package. Typically used
15695     * when cleaning up old installs, or used as a move source.
15696     */
15697    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15698            String resourcePath, String[] instructionSets) {
15699        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15700    }
15701
15702    static abstract class InstallArgs {
15703        /** @see InstallParams#origin */
15704        final OriginInfo origin;
15705        /** @see InstallParams#move */
15706        final MoveInfo move;
15707
15708        final IPackageInstallObserver2 observer;
15709        // Always refers to PackageManager flags only
15710        final int installFlags;
15711        final String installerPackageName;
15712        final String volumeUuid;
15713        final UserHandle user;
15714        final String abiOverride;
15715        final String[] installGrantPermissions;
15716        /** If non-null, drop an async trace when the install completes */
15717        final String traceMethod;
15718        final int traceCookie;
15719        final PackageParser.SigningDetails signingDetails;
15720        final int installReason;
15721
15722        // The list of instruction sets supported by this app. This is currently
15723        // only used during the rmdex() phase to clean up resources. We can get rid of this
15724        // if we move dex files under the common app path.
15725        /* nullable */ String[] instructionSets;
15726
15727        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15728                int installFlags, String installerPackageName, String volumeUuid,
15729                UserHandle user, String[] instructionSets,
15730                String abiOverride, String[] installGrantPermissions,
15731                String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
15732                int installReason) {
15733            this.origin = origin;
15734            this.move = move;
15735            this.installFlags = installFlags;
15736            this.observer = observer;
15737            this.installerPackageName = installerPackageName;
15738            this.volumeUuid = volumeUuid;
15739            this.user = user;
15740            this.instructionSets = instructionSets;
15741            this.abiOverride = abiOverride;
15742            this.installGrantPermissions = installGrantPermissions;
15743            this.traceMethod = traceMethod;
15744            this.traceCookie = traceCookie;
15745            this.signingDetails = signingDetails;
15746            this.installReason = installReason;
15747        }
15748
15749        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15750        abstract int doPreInstall(int status);
15751
15752        /**
15753         * Rename package into final resting place. All paths on the given
15754         * scanned package should be updated to reflect the rename.
15755         */
15756        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15757        abstract int doPostInstall(int status, int uid);
15758
15759        /** @see PackageSettingBase#codePathString */
15760        abstract String getCodePath();
15761        /** @see PackageSettingBase#resourcePathString */
15762        abstract String getResourcePath();
15763
15764        // Need installer lock especially for dex file removal.
15765        abstract void cleanUpResourcesLI();
15766        abstract boolean doPostDeleteLI(boolean delete);
15767
15768        /**
15769         * Called before the source arguments are copied. This is used mostly
15770         * for MoveParams when it needs to read the source file to put it in the
15771         * destination.
15772         */
15773        int doPreCopy() {
15774            return PackageManager.INSTALL_SUCCEEDED;
15775        }
15776
15777        /**
15778         * Called after the source arguments are copied. This is used mostly for
15779         * MoveParams when it needs to read the source file to put it in the
15780         * destination.
15781         */
15782        int doPostCopy(int uid) {
15783            return PackageManager.INSTALL_SUCCEEDED;
15784        }
15785
15786        protected boolean isFwdLocked() {
15787            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15788        }
15789
15790        protected boolean isExternalAsec() {
15791            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15792        }
15793
15794        protected boolean isEphemeral() {
15795            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15796        }
15797
15798        UserHandle getUser() {
15799            return user;
15800        }
15801    }
15802
15803    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15804        if (!allCodePaths.isEmpty()) {
15805            if (instructionSets == null) {
15806                throw new IllegalStateException("instructionSet == null");
15807            }
15808            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15809            for (String codePath : allCodePaths) {
15810                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15811                    try {
15812                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15813                    } catch (InstallerException ignored) {
15814                    }
15815                }
15816            }
15817        }
15818    }
15819
15820    /**
15821     * Logic to handle installation of non-ASEC applications, including copying
15822     * and renaming logic.
15823     */
15824    class FileInstallArgs extends InstallArgs {
15825        private File codeFile;
15826        private File resourceFile;
15827
15828        // Example topology:
15829        // /data/app/com.example/base.apk
15830        // /data/app/com.example/split_foo.apk
15831        // /data/app/com.example/lib/arm/libfoo.so
15832        // /data/app/com.example/lib/arm64/libfoo.so
15833        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15834
15835        /** New install */
15836        FileInstallArgs(InstallParams params) {
15837            super(params.origin, params.move, params.observer, params.installFlags,
15838                    params.installerPackageName, params.volumeUuid,
15839                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15840                    params.grantedRuntimePermissions,
15841                    params.traceMethod, params.traceCookie, params.signingDetails,
15842                    params.installReason);
15843            if (isFwdLocked()) {
15844                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15845            }
15846        }
15847
15848        /** Existing install */
15849        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15850            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15851                    null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15852                    PackageManager.INSTALL_REASON_UNKNOWN);
15853            this.codeFile = (codePath != null) ? new File(codePath) : null;
15854            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15855        }
15856
15857        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15858            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15859            try {
15860                return doCopyApk(imcs, temp);
15861            } finally {
15862                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15863            }
15864        }
15865
15866        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15867            if (origin.staged) {
15868                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15869                codeFile = origin.file;
15870                resourceFile = origin.file;
15871                return PackageManager.INSTALL_SUCCEEDED;
15872            }
15873
15874            try {
15875                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15876                final File tempDir =
15877                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15878                codeFile = tempDir;
15879                resourceFile = tempDir;
15880            } catch (IOException e) {
15881                Slog.w(TAG, "Failed to create copy file: " + e);
15882                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15883            }
15884
15885            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15886                @Override
15887                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15888                    if (!FileUtils.isValidExtFilename(name)) {
15889                        throw new IllegalArgumentException("Invalid filename: " + name);
15890                    }
15891                    try {
15892                        final File file = new File(codeFile, name);
15893                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15894                                O_RDWR | O_CREAT, 0644);
15895                        Os.chmod(file.getAbsolutePath(), 0644);
15896                        return new ParcelFileDescriptor(fd);
15897                    } catch (ErrnoException e) {
15898                        throw new RemoteException("Failed to open: " + e.getMessage());
15899                    }
15900                }
15901            };
15902
15903            int ret = PackageManager.INSTALL_SUCCEEDED;
15904            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15905            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15906                Slog.e(TAG, "Failed to copy package");
15907                return ret;
15908            }
15909
15910            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15911            NativeLibraryHelper.Handle handle = null;
15912            try {
15913                handle = NativeLibraryHelper.Handle.create(codeFile);
15914                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15915                        abiOverride);
15916            } catch (IOException e) {
15917                Slog.e(TAG, "Copying native libraries failed", e);
15918                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15919            } finally {
15920                IoUtils.closeQuietly(handle);
15921            }
15922
15923            return ret;
15924        }
15925
15926        int doPreInstall(int status) {
15927            if (status != PackageManager.INSTALL_SUCCEEDED) {
15928                cleanUp();
15929            }
15930            return status;
15931        }
15932
15933        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15934            if (status != PackageManager.INSTALL_SUCCEEDED) {
15935                cleanUp();
15936                return false;
15937            }
15938
15939            final File targetDir = codeFile.getParentFile();
15940            final File beforeCodeFile = codeFile;
15941            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15942
15943            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15944            try {
15945                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15946            } catch (ErrnoException e) {
15947                Slog.w(TAG, "Failed to rename", e);
15948                return false;
15949            }
15950
15951            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15952                Slog.w(TAG, "Failed to restorecon");
15953                return false;
15954            }
15955
15956            // Reflect the rename internally
15957            codeFile = afterCodeFile;
15958            resourceFile = afterCodeFile;
15959
15960            // Reflect the rename in scanned details
15961            try {
15962                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15963            } catch (IOException e) {
15964                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15965                return false;
15966            }
15967            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15968                    afterCodeFile, pkg.baseCodePath));
15969            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15970                    afterCodeFile, pkg.splitCodePaths));
15971
15972            // Reflect the rename in app info
15973            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15974            pkg.setApplicationInfoCodePath(pkg.codePath);
15975            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15976            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15977            pkg.setApplicationInfoResourcePath(pkg.codePath);
15978            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15979            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15980
15981            return true;
15982        }
15983
15984        int doPostInstall(int status, int uid) {
15985            if (status != PackageManager.INSTALL_SUCCEEDED) {
15986                cleanUp();
15987            }
15988            return status;
15989        }
15990
15991        @Override
15992        String getCodePath() {
15993            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15994        }
15995
15996        @Override
15997        String getResourcePath() {
15998            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15999        }
16000
16001        private boolean cleanUp() {
16002            if (codeFile == null || !codeFile.exists()) {
16003                return false;
16004            }
16005
16006            removeCodePathLI(codeFile);
16007
16008            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16009                resourceFile.delete();
16010            }
16011
16012            return true;
16013        }
16014
16015        void cleanUpResourcesLI() {
16016            // Try enumerating all code paths before deleting
16017            List<String> allCodePaths = Collections.EMPTY_LIST;
16018            if (codeFile != null && codeFile.exists()) {
16019                try {
16020                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16021                    allCodePaths = pkg.getAllCodePaths();
16022                } catch (PackageParserException e) {
16023                    // Ignored; we tried our best
16024                }
16025            }
16026
16027            cleanUp();
16028            removeDexFiles(allCodePaths, instructionSets);
16029        }
16030
16031        boolean doPostDeleteLI(boolean delete) {
16032            // XXX err, shouldn't we respect the delete flag?
16033            cleanUpResourcesLI();
16034            return true;
16035        }
16036    }
16037
16038    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16039            PackageManagerException {
16040        if (copyRet < 0) {
16041            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16042                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16043                throw new PackageManagerException(copyRet, message);
16044            }
16045        }
16046    }
16047
16048    /**
16049     * Extract the StorageManagerService "container ID" from the full code path of an
16050     * .apk.
16051     */
16052    static String cidFromCodePath(String fullCodePath) {
16053        int eidx = fullCodePath.lastIndexOf("/");
16054        String subStr1 = fullCodePath.substring(0, eidx);
16055        int sidx = subStr1.lastIndexOf("/");
16056        return subStr1.substring(sidx+1, eidx);
16057    }
16058
16059    /**
16060     * Logic to handle movement of existing installed applications.
16061     */
16062    class MoveInstallArgs extends InstallArgs {
16063        private File codeFile;
16064        private File resourceFile;
16065
16066        /** New install */
16067        MoveInstallArgs(InstallParams params) {
16068            super(params.origin, params.move, params.observer, params.installFlags,
16069                    params.installerPackageName, params.volumeUuid,
16070                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16071                    params.grantedRuntimePermissions,
16072                    params.traceMethod, params.traceCookie, params.signingDetails,
16073                    params.installReason);
16074        }
16075
16076        int copyApk(IMediaContainerService imcs, boolean temp) {
16077            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16078                    + move.fromUuid + " to " + move.toUuid);
16079            synchronized (mInstaller) {
16080                try {
16081                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16082                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16083                } catch (InstallerException e) {
16084                    Slog.w(TAG, "Failed to move app", e);
16085                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16086                }
16087            }
16088
16089            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16090            resourceFile = codeFile;
16091            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16092
16093            return PackageManager.INSTALL_SUCCEEDED;
16094        }
16095
16096        int doPreInstall(int status) {
16097            if (status != PackageManager.INSTALL_SUCCEEDED) {
16098                cleanUp(move.toUuid);
16099            }
16100            return status;
16101        }
16102
16103        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16104            if (status != PackageManager.INSTALL_SUCCEEDED) {
16105                cleanUp(move.toUuid);
16106                return false;
16107            }
16108
16109            // Reflect the move in app info
16110            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16111            pkg.setApplicationInfoCodePath(pkg.codePath);
16112            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16113            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16114            pkg.setApplicationInfoResourcePath(pkg.codePath);
16115            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16116            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16117
16118            return true;
16119        }
16120
16121        int doPostInstall(int status, int uid) {
16122            if (status == PackageManager.INSTALL_SUCCEEDED) {
16123                cleanUp(move.fromUuid);
16124            } else {
16125                cleanUp(move.toUuid);
16126            }
16127            return status;
16128        }
16129
16130        @Override
16131        String getCodePath() {
16132            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16133        }
16134
16135        @Override
16136        String getResourcePath() {
16137            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16138        }
16139
16140        private boolean cleanUp(String volumeUuid) {
16141            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16142                    move.dataAppName);
16143            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16144            final int[] userIds = sUserManager.getUserIds();
16145            synchronized (mInstallLock) {
16146                // Clean up both app data and code
16147                // All package moves are frozen until finished
16148                for (int userId : userIds) {
16149                    try {
16150                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16151                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16152                    } catch (InstallerException e) {
16153                        Slog.w(TAG, String.valueOf(e));
16154                    }
16155                }
16156                removeCodePathLI(codeFile);
16157            }
16158            return true;
16159        }
16160
16161        void cleanUpResourcesLI() {
16162            throw new UnsupportedOperationException();
16163        }
16164
16165        boolean doPostDeleteLI(boolean delete) {
16166            throw new UnsupportedOperationException();
16167        }
16168    }
16169
16170    static String getAsecPackageName(String packageCid) {
16171        int idx = packageCid.lastIndexOf("-");
16172        if (idx == -1) {
16173            return packageCid;
16174        }
16175        return packageCid.substring(0, idx);
16176    }
16177
16178    // Utility method used to create code paths based on package name and available index.
16179    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16180        String idxStr = "";
16181        int idx = 1;
16182        // Fall back to default value of idx=1 if prefix is not
16183        // part of oldCodePath
16184        if (oldCodePath != null) {
16185            String subStr = oldCodePath;
16186            // Drop the suffix right away
16187            if (suffix != null && subStr.endsWith(suffix)) {
16188                subStr = subStr.substring(0, subStr.length() - suffix.length());
16189            }
16190            // If oldCodePath already contains prefix find out the
16191            // ending index to either increment or decrement.
16192            int sidx = subStr.lastIndexOf(prefix);
16193            if (sidx != -1) {
16194                subStr = subStr.substring(sidx + prefix.length());
16195                if (subStr != null) {
16196                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16197                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16198                    }
16199                    try {
16200                        idx = Integer.parseInt(subStr);
16201                        if (idx <= 1) {
16202                            idx++;
16203                        } else {
16204                            idx--;
16205                        }
16206                    } catch(NumberFormatException e) {
16207                    }
16208                }
16209            }
16210        }
16211        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16212        return prefix + idxStr;
16213    }
16214
16215    private File getNextCodePath(File targetDir, String packageName) {
16216        File result;
16217        SecureRandom random = new SecureRandom();
16218        byte[] bytes = new byte[16];
16219        do {
16220            random.nextBytes(bytes);
16221            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16222            result = new File(targetDir, packageName + "-" + suffix);
16223        } while (result.exists());
16224        return result;
16225    }
16226
16227    // Utility method that returns the relative package path with respect
16228    // to the installation directory. Like say for /data/data/com.test-1.apk
16229    // string com.test-1 is returned.
16230    static String deriveCodePathName(String codePath) {
16231        if (codePath == null) {
16232            return null;
16233        }
16234        final File codeFile = new File(codePath);
16235        final String name = codeFile.getName();
16236        if (codeFile.isDirectory()) {
16237            return name;
16238        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16239            final int lastDot = name.lastIndexOf('.');
16240            return name.substring(0, lastDot);
16241        } else {
16242            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16243            return null;
16244        }
16245    }
16246
16247    static class PackageInstalledInfo {
16248        String name;
16249        int uid;
16250        // The set of users that originally had this package installed.
16251        int[] origUsers;
16252        // The set of users that now have this package installed.
16253        int[] newUsers;
16254        PackageParser.Package pkg;
16255        int returnCode;
16256        String returnMsg;
16257        String installerPackageName;
16258        PackageRemovedInfo removedInfo;
16259        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16260
16261        public void setError(int code, String msg) {
16262            setReturnCode(code);
16263            setReturnMessage(msg);
16264            Slog.w(TAG, msg);
16265        }
16266
16267        public void setError(String msg, PackageParserException e) {
16268            setReturnCode(e.error);
16269            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16270            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16271            for (int i = 0; i < childCount; i++) {
16272                addedChildPackages.valueAt(i).setError(msg, e);
16273            }
16274            Slog.w(TAG, msg, e);
16275        }
16276
16277        public void setError(String msg, PackageManagerException e) {
16278            returnCode = e.error;
16279            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16280            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16281            for (int i = 0; i < childCount; i++) {
16282                addedChildPackages.valueAt(i).setError(msg, e);
16283            }
16284            Slog.w(TAG, msg, e);
16285        }
16286
16287        public void setReturnCode(int returnCode) {
16288            this.returnCode = returnCode;
16289            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16290            for (int i = 0; i < childCount; i++) {
16291                addedChildPackages.valueAt(i).returnCode = returnCode;
16292            }
16293        }
16294
16295        private void setReturnMessage(String returnMsg) {
16296            this.returnMsg = returnMsg;
16297            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16298            for (int i = 0; i < childCount; i++) {
16299                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16300            }
16301        }
16302
16303        // In some error cases we want to convey more info back to the observer
16304        String origPackage;
16305        String origPermission;
16306    }
16307
16308    /*
16309     * Install a non-existing package.
16310     */
16311    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16312            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16313            String volumeUuid, PackageInstalledInfo res, int installReason) {
16314        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16315
16316        // Remember this for later, in case we need to rollback this install
16317        String pkgName = pkg.packageName;
16318
16319        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16320
16321        synchronized(mPackages) {
16322            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16323            if (renamedPackage != null) {
16324                // A package with the same name is already installed, though
16325                // it has been renamed to an older name.  The package we
16326                // are trying to install should be installed as an update to
16327                // the existing one, but that has not been requested, so bail.
16328                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16329                        + " without first uninstalling package running as "
16330                        + renamedPackage);
16331                return;
16332            }
16333            if (mPackages.containsKey(pkgName)) {
16334                // Don't allow installation over an existing package with the same name.
16335                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16336                        + " without first uninstalling.");
16337                return;
16338            }
16339        }
16340
16341        try {
16342            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
16343                    System.currentTimeMillis(), user);
16344
16345            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16346
16347            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16348                prepareAppDataAfterInstallLIF(newPackage);
16349
16350            } else {
16351                // Remove package from internal structures, but keep around any
16352                // data that might have already existed
16353                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16354                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16355            }
16356        } catch (PackageManagerException e) {
16357            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16358        }
16359
16360        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16361    }
16362
16363    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16364        try (DigestInputStream digestStream =
16365                new DigestInputStream(new FileInputStream(file), digest)) {
16366            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16367        }
16368    }
16369
16370    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16371            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16372            PackageInstalledInfo res, int installReason) {
16373        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16374
16375        final PackageParser.Package oldPackage;
16376        final PackageSetting ps;
16377        final String pkgName = pkg.packageName;
16378        final int[] allUsers;
16379        final int[] installedUsers;
16380
16381        synchronized(mPackages) {
16382            oldPackage = mPackages.get(pkgName);
16383            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16384
16385            // don't allow upgrade to target a release SDK from a pre-release SDK
16386            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16387                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16388            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16389                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16390            if (oldTargetsPreRelease
16391                    && !newTargetsPreRelease
16392                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16393                Slog.w(TAG, "Can't install package targeting released sdk");
16394                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16395                return;
16396            }
16397
16398            ps = mSettings.mPackages.get(pkgName);
16399
16400            // verify signatures are valid
16401            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16402            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
16403                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
16404                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16405                            "New package not signed by keys specified by upgrade-keysets: "
16406                                    + pkgName);
16407                    return;
16408                }
16409            } else {
16410
16411                // default to original signature matching
16412                if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails,
16413                        PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)
16414                                && !oldPackage.mSigningDetails.checkCapability(
16415                                        pkg.mSigningDetails,
16416                                        PackageParser.SigningDetails.CertCapabilities.ROLLBACK)) {
16417                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16418                            "New package has a different signature: " + pkgName);
16419                    return;
16420                }
16421            }
16422
16423            // don't allow a system upgrade unless the upgrade hash matches
16424            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
16425                byte[] digestBytes = null;
16426                try {
16427                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16428                    updateDigest(digest, new File(pkg.baseCodePath));
16429                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16430                        for (String path : pkg.splitCodePaths) {
16431                            updateDigest(digest, new File(path));
16432                        }
16433                    }
16434                    digestBytes = digest.digest();
16435                } catch (NoSuchAlgorithmException | IOException e) {
16436                    res.setError(INSTALL_FAILED_INVALID_APK,
16437                            "Could not compute hash: " + pkgName);
16438                    return;
16439                }
16440                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16441                    res.setError(INSTALL_FAILED_INVALID_APK,
16442                            "New package fails restrict-update check: " + pkgName);
16443                    return;
16444                }
16445                // retain upgrade restriction
16446                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16447            }
16448
16449            // Check for shared user id changes
16450            String invalidPackageName =
16451                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16452            if (invalidPackageName != null) {
16453                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16454                        "Package " + invalidPackageName + " tried to change user "
16455                                + oldPackage.mSharedUserId);
16456                return;
16457            }
16458
16459            // check if the new package supports all of the abis which the old package supports
16460            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
16461            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
16462            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
16463                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16464                        "Update to package " + pkgName + " doesn't support multi arch");
16465                return;
16466            }
16467
16468            // In case of rollback, remember per-user/profile install state
16469            allUsers = sUserManager.getUserIds();
16470            installedUsers = ps.queryInstalledUsers(allUsers, true);
16471
16472            // don't allow an upgrade from full to ephemeral
16473            if (isInstantApp) {
16474                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16475                    for (int currentUser : allUsers) {
16476                        if (!ps.getInstantApp(currentUser)) {
16477                            // can't downgrade from full to instant
16478                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16479                                    + " for user: " + currentUser);
16480                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16481                            return;
16482                        }
16483                    }
16484                } else if (!ps.getInstantApp(user.getIdentifier())) {
16485                    // can't downgrade from full to instant
16486                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16487                            + " for user: " + user.getIdentifier());
16488                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16489                    return;
16490                }
16491            }
16492        }
16493
16494        // Update what is removed
16495        res.removedInfo = new PackageRemovedInfo(this);
16496        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16497        res.removedInfo.removedPackage = oldPackage.packageName;
16498        res.removedInfo.installerPackageName = ps.installerPackageName;
16499        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16500        res.removedInfo.isUpdate = true;
16501        res.removedInfo.origUsers = installedUsers;
16502        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16503        for (int i = 0; i < installedUsers.length; i++) {
16504            final int userId = installedUsers[i];
16505            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16506        }
16507
16508        final int childCount = (oldPackage.childPackages != null)
16509                ? oldPackage.childPackages.size() : 0;
16510        for (int i = 0; i < childCount; i++) {
16511            boolean childPackageUpdated = false;
16512            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16513            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16514            if (res.addedChildPackages != null) {
16515                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16516                if (childRes != null) {
16517                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16518                    childRes.removedInfo.removedPackage = childPkg.packageName;
16519                    if (childPs != null) {
16520                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16521                    }
16522                    childRes.removedInfo.isUpdate = true;
16523                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16524                    childPackageUpdated = true;
16525                }
16526            }
16527            if (!childPackageUpdated) {
16528                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16529                childRemovedRes.removedPackage = childPkg.packageName;
16530                if (childPs != null) {
16531                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16532                }
16533                childRemovedRes.isUpdate = false;
16534                childRemovedRes.dataRemoved = true;
16535                synchronized (mPackages) {
16536                    if (childPs != null) {
16537                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16538                    }
16539                }
16540                if (res.removedInfo.removedChildPackages == null) {
16541                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16542                }
16543                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16544            }
16545        }
16546
16547        boolean sysPkg = (isSystemApp(oldPackage));
16548        if (sysPkg) {
16549            // Set the system/privileged/oem/vendor/product flags as needed
16550            final boolean privileged =
16551                    (oldPackage.applicationInfo.privateFlags
16552                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16553            final boolean oem =
16554                    (oldPackage.applicationInfo.privateFlags
16555                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16556            final boolean vendor =
16557                    (oldPackage.applicationInfo.privateFlags
16558                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
16559            final boolean product =
16560                    (oldPackage.applicationInfo.privateFlags
16561                            & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
16562            final @ParseFlags int systemParseFlags = parseFlags;
16563            final @ScanFlags int systemScanFlags = scanFlags
16564                    | SCAN_AS_SYSTEM
16565                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
16566                    | (oem ? SCAN_AS_OEM : 0)
16567                    | (vendor ? SCAN_AS_VENDOR : 0)
16568                    | (product ? SCAN_AS_PRODUCT : 0);
16569
16570            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
16571                    user, allUsers, installerPackageName, res, installReason);
16572        } else {
16573            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
16574                    user, allUsers, installerPackageName, res, installReason);
16575        }
16576    }
16577
16578    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16579            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16580            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
16581            String installerPackageName, PackageInstalledInfo res, int installReason) {
16582        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16583                + deletedPackage);
16584
16585        String pkgName = deletedPackage.packageName;
16586        boolean deletedPkg = true;
16587        boolean addedPkg = false;
16588        boolean updatedSettings = false;
16589        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16590        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16591                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16592
16593        final long origUpdateTime = (pkg.mExtras != null)
16594                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16595
16596        // First delete the existing package while retaining the data directory
16597        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16598                res.removedInfo, true, pkg)) {
16599            // If the existing package wasn't successfully deleted
16600            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16601            deletedPkg = false;
16602        } else {
16603            // Successfully deleted the old package; proceed with replace.
16604
16605            // If deleted package lived in a container, give users a chance to
16606            // relinquish resources before killing.
16607            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16608                if (DEBUG_INSTALL) {
16609                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16610                }
16611                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16612                final ArrayList<String> pkgList = new ArrayList<String>(1);
16613                pkgList.add(deletedPackage.applicationInfo.packageName);
16614                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16615            }
16616
16617            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16618                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16619
16620            try {
16621                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
16622                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16623                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16624                        installReason);
16625
16626                // Update the in-memory copy of the previous code paths.
16627                PackageSetting ps = mSettings.mPackages.get(pkgName);
16628                if (!killApp) {
16629                    if (ps.oldCodePaths == null) {
16630                        ps.oldCodePaths = new ArraySet<>();
16631                    }
16632                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16633                    if (deletedPackage.splitCodePaths != null) {
16634                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16635                    }
16636                } else {
16637                    ps.oldCodePaths = null;
16638                }
16639                if (ps.childPackageNames != null) {
16640                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16641                        final String childPkgName = ps.childPackageNames.get(i);
16642                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16643                        childPs.oldCodePaths = ps.oldCodePaths;
16644                    }
16645                }
16646                prepareAppDataAfterInstallLIF(newPackage);
16647                addedPkg = true;
16648                mDexManager.notifyPackageUpdated(newPackage.packageName,
16649                        newPackage.baseCodePath, newPackage.splitCodePaths);
16650            } catch (PackageManagerException e) {
16651                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16652            }
16653        }
16654
16655        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16656            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16657
16658            // Revert all internal state mutations and added folders for the failed install
16659            if (addedPkg) {
16660                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16661                        res.removedInfo, true, null);
16662            }
16663
16664            // Restore the old package
16665            if (deletedPkg) {
16666                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16667                File restoreFile = new File(deletedPackage.codePath);
16668                // Parse old package
16669                boolean oldExternal = isExternal(deletedPackage);
16670                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16671                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16672                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16673                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16674                try {
16675                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16676                            null);
16677                } catch (PackageManagerException e) {
16678                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16679                            + e.getMessage());
16680                    return;
16681                }
16682
16683                synchronized (mPackages) {
16684                    // Ensure the installer package name up to date
16685                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16686
16687                    // Update permissions for restored package
16688                    mPermissionManager.updatePermissions(
16689                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16690                            mPermissionCallback);
16691
16692                    mSettings.writeLPr();
16693                }
16694
16695                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16696            }
16697        } else {
16698            synchronized (mPackages) {
16699                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16700                if (ps != null) {
16701                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16702                    if (res.removedInfo.removedChildPackages != null) {
16703                        final int childCount = res.removedInfo.removedChildPackages.size();
16704                        // Iterate in reverse as we may modify the collection
16705                        for (int i = childCount - 1; i >= 0; i--) {
16706                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16707                            if (res.addedChildPackages.containsKey(childPackageName)) {
16708                                res.removedInfo.removedChildPackages.removeAt(i);
16709                            } else {
16710                                PackageRemovedInfo childInfo = res.removedInfo
16711                                        .removedChildPackages.valueAt(i);
16712                                childInfo.removedForAllUsers = mPackages.get(
16713                                        childInfo.removedPackage) == null;
16714                            }
16715                        }
16716                    }
16717                }
16718            }
16719        }
16720    }
16721
16722    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16723            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16724            final @ScanFlags int scanFlags, UserHandle user,
16725            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16726            int installReason) {
16727        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16728                + ", old=" + deletedPackage);
16729
16730        final boolean disabledSystem;
16731
16732        // Remove existing system package
16733        removePackageLI(deletedPackage, true);
16734
16735        synchronized (mPackages) {
16736            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16737        }
16738        if (!disabledSystem) {
16739            // We didn't need to disable the .apk as a current system package,
16740            // which means we are replacing another update that is already
16741            // installed.  We need to make sure to delete the older one's .apk.
16742            res.removedInfo.args = createInstallArgsForExisting(0,
16743                    deletedPackage.applicationInfo.getCodePath(),
16744                    deletedPackage.applicationInfo.getResourcePath(),
16745                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16746        } else {
16747            res.removedInfo.args = null;
16748        }
16749
16750        // Successfully disabled the old package. Now proceed with re-installation
16751        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16752                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16753
16754        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16755        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16756                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16757
16758        PackageParser.Package newPackage = null;
16759        try {
16760            // Add the package to the internal data structures
16761            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16762
16763            // Set the update and install times
16764            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16765            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16766                    System.currentTimeMillis());
16767
16768            // Update the package dynamic state if succeeded
16769            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16770                // Now that the install succeeded make sure we remove data
16771                // directories for any child package the update removed.
16772                final int deletedChildCount = (deletedPackage.childPackages != null)
16773                        ? deletedPackage.childPackages.size() : 0;
16774                final int newChildCount = (newPackage.childPackages != null)
16775                        ? newPackage.childPackages.size() : 0;
16776                for (int i = 0; i < deletedChildCount; i++) {
16777                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16778                    boolean childPackageDeleted = true;
16779                    for (int j = 0; j < newChildCount; j++) {
16780                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16781                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16782                            childPackageDeleted = false;
16783                            break;
16784                        }
16785                    }
16786                    if (childPackageDeleted) {
16787                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16788                                deletedChildPkg.packageName);
16789                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16790                            PackageRemovedInfo removedChildRes = res.removedInfo
16791                                    .removedChildPackages.get(deletedChildPkg.packageName);
16792                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16793                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16794                        }
16795                    }
16796                }
16797
16798                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16799                        installReason);
16800                prepareAppDataAfterInstallLIF(newPackage);
16801
16802                mDexManager.notifyPackageUpdated(newPackage.packageName,
16803                            newPackage.baseCodePath, newPackage.splitCodePaths);
16804            }
16805        } catch (PackageManagerException e) {
16806            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16807            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16808        }
16809
16810        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16811            // Re installation failed. Restore old information
16812            // Remove new pkg information
16813            if (newPackage != null) {
16814                removeInstalledPackageLI(newPackage, true);
16815            }
16816            // Add back the old system package
16817            try {
16818                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16819            } catch (PackageManagerException e) {
16820                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16821            }
16822
16823            synchronized (mPackages) {
16824                if (disabledSystem) {
16825                    enableSystemPackageLPw(deletedPackage);
16826                }
16827
16828                // Ensure the installer package name up to date
16829                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16830
16831                // Update permissions for restored package
16832                mPermissionManager.updatePermissions(
16833                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16834                        mPermissionCallback);
16835
16836                mSettings.writeLPr();
16837            }
16838
16839            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16840                    + " after failed upgrade");
16841        }
16842    }
16843
16844    /**
16845     * Checks whether the parent or any of the child packages have a change shared
16846     * user. For a package to be a valid update the shred users of the parent and
16847     * the children should match. We may later support changing child shared users.
16848     * @param oldPkg The updated package.
16849     * @param newPkg The update package.
16850     * @return The shared user that change between the versions.
16851     */
16852    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16853            PackageParser.Package newPkg) {
16854        // Check parent shared user
16855        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16856            return newPkg.packageName;
16857        }
16858        // Check child shared users
16859        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16860        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16861        for (int i = 0; i < newChildCount; i++) {
16862            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16863            // If this child was present, did it have the same shared user?
16864            for (int j = 0; j < oldChildCount; j++) {
16865                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16866                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16867                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16868                    return newChildPkg.packageName;
16869                }
16870            }
16871        }
16872        return null;
16873    }
16874
16875    private void removeNativeBinariesLI(PackageSetting ps) {
16876        // Remove the lib path for the parent package
16877        if (ps != null) {
16878            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16879            // Remove the lib path for the child packages
16880            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16881            for (int i = 0; i < childCount; i++) {
16882                PackageSetting childPs = null;
16883                synchronized (mPackages) {
16884                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16885                }
16886                if (childPs != null) {
16887                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16888                            .legacyNativeLibraryPathString);
16889                }
16890            }
16891        }
16892    }
16893
16894    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16895        // Enable the parent package
16896        mSettings.enableSystemPackageLPw(pkg.packageName);
16897        // Enable the child packages
16898        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16899        for (int i = 0; i < childCount; i++) {
16900            PackageParser.Package childPkg = pkg.childPackages.get(i);
16901            mSettings.enableSystemPackageLPw(childPkg.packageName);
16902        }
16903    }
16904
16905    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16906            PackageParser.Package newPkg) {
16907        // Disable the parent package (parent always replaced)
16908        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16909        // Disable the child packages
16910        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16911        for (int i = 0; i < childCount; i++) {
16912            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16913            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16914            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16915        }
16916        return disabled;
16917    }
16918
16919    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16920            String installerPackageName) {
16921        // Enable the parent package
16922        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16923        // Enable the child packages
16924        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16925        for (int i = 0; i < childCount; i++) {
16926            PackageParser.Package childPkg = pkg.childPackages.get(i);
16927            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16928        }
16929    }
16930
16931    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16932            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16933        // Update the parent package setting
16934        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16935                res, user, installReason);
16936        // Update the child packages setting
16937        final int childCount = (newPackage.childPackages != null)
16938                ? newPackage.childPackages.size() : 0;
16939        for (int i = 0; i < childCount; i++) {
16940            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16941            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16942            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16943                    childRes.origUsers, childRes, user, installReason);
16944        }
16945    }
16946
16947    private void updateSettingsInternalLI(PackageParser.Package pkg,
16948            String installerPackageName, int[] allUsers, int[] installedForUsers,
16949            PackageInstalledInfo res, UserHandle user, int installReason) {
16950        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16951
16952        final String pkgName = pkg.packageName;
16953
16954        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16955        synchronized (mPackages) {
16956// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16957            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16958                    mPermissionCallback);
16959            // For system-bundled packages, we assume that installing an upgraded version
16960            // of the package implies that the user actually wants to run that new code,
16961            // so we enable the package.
16962            PackageSetting ps = mSettings.mPackages.get(pkgName);
16963            final int userId = user.getIdentifier();
16964            if (ps != null) {
16965                if (isSystemApp(pkg)) {
16966                    if (DEBUG_INSTALL) {
16967                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16968                    }
16969                    // Enable system package for requested users
16970                    if (res.origUsers != null) {
16971                        for (int origUserId : res.origUsers) {
16972                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16973                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16974                                        origUserId, installerPackageName);
16975                            }
16976                        }
16977                    }
16978                    // Also convey the prior install/uninstall state
16979                    if (allUsers != null && installedForUsers != null) {
16980                        for (int currentUserId : allUsers) {
16981                            final boolean installed = ArrayUtils.contains(
16982                                    installedForUsers, currentUserId);
16983                            if (DEBUG_INSTALL) {
16984                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16985                            }
16986                            ps.setInstalled(installed, currentUserId);
16987                        }
16988                        // these install state changes will be persisted in the
16989                        // upcoming call to mSettings.writeLPr().
16990                    }
16991                }
16992                // It's implied that when a user requests installation, they want the app to be
16993                // installed and enabled.
16994                if (userId != UserHandle.USER_ALL) {
16995                    ps.setInstalled(true, userId);
16996                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16997                }
16998
16999                // When replacing an existing package, preserve the original install reason for all
17000                // users that had the package installed before.
17001                final Set<Integer> previousUserIds = new ArraySet<>();
17002                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17003                    final int installReasonCount = res.removedInfo.installReasons.size();
17004                    for (int i = 0; i < installReasonCount; i++) {
17005                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17006                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17007                        ps.setInstallReason(previousInstallReason, previousUserId);
17008                        previousUserIds.add(previousUserId);
17009                    }
17010                }
17011
17012                // Set install reason for users that are having the package newly installed.
17013                if (userId == UserHandle.USER_ALL) {
17014                    for (int currentUserId : sUserManager.getUserIds()) {
17015                        if (!previousUserIds.contains(currentUserId)) {
17016                            ps.setInstallReason(installReason, currentUserId);
17017                        }
17018                    }
17019                } else if (!previousUserIds.contains(userId)) {
17020                    ps.setInstallReason(installReason, userId);
17021                }
17022                mSettings.writeKernelMappingLPr(ps);
17023            }
17024            res.name = pkgName;
17025            res.uid = pkg.applicationInfo.uid;
17026            res.pkg = pkg;
17027            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17028            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17029            //to update install status
17030            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17031            mSettings.writeLPr();
17032            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17033        }
17034
17035        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17036    }
17037
17038    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17039        try {
17040            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17041            installPackageLI(args, res);
17042        } finally {
17043            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17044        }
17045    }
17046
17047    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17048        final int installFlags = args.installFlags;
17049        final String installerPackageName = args.installerPackageName;
17050        final String volumeUuid = args.volumeUuid;
17051        final File tmpPackageFile = new File(args.getCodePath());
17052        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17053        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17054                || (args.volumeUuid != null));
17055        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17056        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17057        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17058        final boolean virtualPreload =
17059                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
17060        boolean replace = false;
17061        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17062        if (args.move != null) {
17063            // moving a complete application; perform an initial scan on the new install location
17064            scanFlags |= SCAN_INITIAL;
17065        }
17066        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17067            scanFlags |= SCAN_DONT_KILL_APP;
17068        }
17069        if (instantApp) {
17070            scanFlags |= SCAN_AS_INSTANT_APP;
17071        }
17072        if (fullApp) {
17073            scanFlags |= SCAN_AS_FULL_APP;
17074        }
17075        if (virtualPreload) {
17076            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
17077        }
17078
17079        // Result object to be returned
17080        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17081        res.installerPackageName = installerPackageName;
17082
17083        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17084
17085        // Sanity check
17086        if (instantApp && (forwardLocked || onExternal)) {
17087            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17088                    + " external=" + onExternal);
17089            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17090            return;
17091        }
17092
17093        // Retrieve PackageSettings and parse package
17094        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17095                | PackageParser.PARSE_ENFORCE_CODE
17096                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17097                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17098                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17099        PackageParser pp = new PackageParser();
17100        pp.setSeparateProcesses(mSeparateProcesses);
17101        pp.setDisplayMetrics(mMetrics);
17102        pp.setCallback(mPackageParserCallback);
17103
17104        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17105        final PackageParser.Package pkg;
17106        try {
17107            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17108            DexMetadataHelper.validatePackageDexMetadata(pkg);
17109        } catch (PackageParserException e) {
17110            res.setError("Failed parse during installPackageLI", e);
17111            return;
17112        } finally {
17113            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17114        }
17115
17116        // Instant apps have several additional install-time checks.
17117        if (instantApp) {
17118            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
17119                Slog.w(TAG,
17120                        "Instant app package " + pkg.packageName + " does not target at least O");
17121                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17122                        "Instant app package must target at least O");
17123                return;
17124            }
17125            if (pkg.applicationInfo.targetSandboxVersion != 2) {
17126                Slog.w(TAG, "Instant app package " + pkg.packageName
17127                        + " does not target targetSandboxVersion 2");
17128                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17129                        "Instant app package must use targetSandboxVersion 2");
17130                return;
17131            }
17132            if (pkg.mSharedUserId != null) {
17133                Slog.w(TAG, "Instant app package " + pkg.packageName
17134                        + " may not declare sharedUserId.");
17135                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17136                        "Instant app package may not declare a sharedUserId");
17137                return;
17138            }
17139        }
17140
17141        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17142            // Static shared libraries have synthetic package names
17143            renameStaticSharedLibraryPackage(pkg);
17144
17145            // No static shared libs on external storage
17146            if (onExternal) {
17147                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17148                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17149                        "Packages declaring static-shared libs cannot be updated");
17150                return;
17151            }
17152        }
17153
17154        // If we are installing a clustered package add results for the children
17155        if (pkg.childPackages != null) {
17156            synchronized (mPackages) {
17157                final int childCount = pkg.childPackages.size();
17158                for (int i = 0; i < childCount; i++) {
17159                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17160                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17161                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17162                    childRes.pkg = childPkg;
17163                    childRes.name = childPkg.packageName;
17164                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17165                    if (childPs != null) {
17166                        childRes.origUsers = childPs.queryInstalledUsers(
17167                                sUserManager.getUserIds(), true);
17168                    }
17169                    if ((mPackages.containsKey(childPkg.packageName))) {
17170                        childRes.removedInfo = new PackageRemovedInfo(this);
17171                        childRes.removedInfo.removedPackage = childPkg.packageName;
17172                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17173                    }
17174                    if (res.addedChildPackages == null) {
17175                        res.addedChildPackages = new ArrayMap<>();
17176                    }
17177                    res.addedChildPackages.put(childPkg.packageName, childRes);
17178                }
17179            }
17180        }
17181
17182        // If package doesn't declare API override, mark that we have an install
17183        // time CPU ABI override.
17184        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17185            pkg.cpuAbiOverride = args.abiOverride;
17186        }
17187
17188        String pkgName = res.name = pkg.packageName;
17189        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17190            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17191                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17192                return;
17193            }
17194        }
17195
17196        try {
17197            // either use what we've been given or parse directly from the APK
17198            if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
17199                pkg.setSigningDetails(args.signingDetails);
17200            } else {
17201                PackageParser.collectCertificates(pkg, false /* skipVerify */);
17202            }
17203        } catch (PackageParserException e) {
17204            res.setError("Failed collect during installPackageLI", e);
17205            return;
17206        }
17207
17208        if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
17209                < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
17210            Slog.w(TAG, "Instant app package " + pkg.packageName
17211                    + " is not signed with at least APK Signature Scheme v2");
17212            res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17213                    "Instant app package must be signed with APK Signature Scheme v2 or greater");
17214            return;
17215        }
17216
17217        // Get rid of all references to package scan path via parser.
17218        pp = null;
17219        String oldCodePath = null;
17220        boolean systemApp = false;
17221        synchronized (mPackages) {
17222            // Check if installing already existing package
17223            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17224                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17225                if (pkg.mOriginalPackages != null
17226                        && pkg.mOriginalPackages.contains(oldName)
17227                        && mPackages.containsKey(oldName)) {
17228                    // This package is derived from an original package,
17229                    // and this device has been updating from that original
17230                    // name.  We must continue using the original name, so
17231                    // rename the new package here.
17232                    pkg.setPackageName(oldName);
17233                    pkgName = pkg.packageName;
17234                    replace = true;
17235                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17236                            + oldName + " pkgName=" + pkgName);
17237                } else if (mPackages.containsKey(pkgName)) {
17238                    // This package, under its official name, already exists
17239                    // on the device; we should replace it.
17240                    replace = true;
17241                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17242                }
17243
17244                // Child packages are installed through the parent package
17245                if (pkg.parentPackage != null) {
17246                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17247                            "Package " + pkg.packageName + " is child of package "
17248                                    + pkg.parentPackage.parentPackage + ". Child packages "
17249                                    + "can be updated only through the parent package.");
17250                    return;
17251                }
17252
17253                if (replace) {
17254                    // Prevent apps opting out from runtime permissions
17255                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17256                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17257                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17258                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17259                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17260                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17261                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17262                                        + " doesn't support runtime permissions but the old"
17263                                        + " target SDK " + oldTargetSdk + " does.");
17264                        return;
17265                    }
17266                    // Prevent persistent apps from being updated
17267                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
17268                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
17269                                "Package " + oldPackage.packageName + " is a persistent app. "
17270                                        + "Persistent apps are not updateable.");
17271                        return;
17272                    }
17273                    // Prevent installing of child packages
17274                    if (oldPackage.parentPackage != null) {
17275                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17276                                "Package " + pkg.packageName + " is child of package "
17277                                        + oldPackage.parentPackage + ". Child packages "
17278                                        + "can be updated only through the parent package.");
17279                        return;
17280                    }
17281                }
17282            }
17283
17284            PackageSetting ps = mSettings.mPackages.get(pkgName);
17285            if (ps != null) {
17286                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17287
17288                // Static shared libs have same package with different versions where
17289                // we internally use a synthetic package name to allow multiple versions
17290                // of the same package, therefore we need to compare signatures against
17291                // the package setting for the latest library version.
17292                PackageSetting signatureCheckPs = ps;
17293                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17294                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17295                    if (libraryEntry != null) {
17296                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17297                    }
17298                }
17299
17300                // Quick sanity check that we're signed correctly if updating;
17301                // we'll check this again later when scanning, but we want to
17302                // bail early here before tripping over redefined permissions.
17303                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17304                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
17305                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
17306                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17307                                + pkg.packageName + " upgrade keys do not match the "
17308                                + "previously installed version");
17309                        return;
17310                    }
17311                } else {
17312                    try {
17313                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
17314                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
17315                        // We don't care about disabledPkgSetting on install for now.
17316                        final boolean compatMatch = verifySignatures(
17317                                signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
17318                                compareRecover);
17319                        // The new KeySets will be re-added later in the scanning process.
17320                        if (compatMatch) {
17321                            synchronized (mPackages) {
17322                                ksms.removeAppKeySetDataLPw(pkg.packageName);
17323                            }
17324                        }
17325                    } catch (PackageManagerException e) {
17326                        res.setError(e.error, e.getMessage());
17327                        return;
17328                    }
17329                }
17330
17331                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17332                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17333                    systemApp = (ps.pkg.applicationInfo.flags &
17334                            ApplicationInfo.FLAG_SYSTEM) != 0;
17335                }
17336                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17337            }
17338
17339            int N = pkg.permissions.size();
17340            for (int i = N-1; i >= 0; i--) {
17341                final PackageParser.Permission perm = pkg.permissions.get(i);
17342                final BasePermission bp =
17343                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
17344
17345                // Don't allow anyone but the system to define ephemeral permissions.
17346                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
17347                        && !systemApp) {
17348                    Slog.w(TAG, "Non-System package " + pkg.packageName
17349                            + " attempting to delcare ephemeral permission "
17350                            + perm.info.name + "; Removing ephemeral.");
17351                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
17352                }
17353
17354                // Check whether the newly-scanned package wants to define an already-defined perm
17355                if (bp != null) {
17356                    // If the defining package is signed with our cert, it's okay.  This
17357                    // also includes the "updating the same package" case, of course.
17358                    // "updating same package" could also involve key-rotation.
17359                    final boolean sigsOk;
17360                    final String sourcePackageName = bp.getSourcePackageName();
17361                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17362                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17363                    if (sourcePackageName.equals(pkg.packageName)
17364                            && (ksms.shouldCheckUpgradeKeySetLocked(
17365                                    sourcePackageSetting, scanFlags))) {
17366                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
17367                    } else {
17368
17369                        // in the event of signing certificate rotation, we need to see if the
17370                        // package's certificate has rotated from the current one, or if it is an
17371                        // older certificate with which the current is ok with sharing permissions
17372                        if (sourcePackageSetting.signatures.mSigningDetails.checkCapability(
17373                                        pkg.mSigningDetails,
17374                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17375                            sigsOk = true;
17376                        } else if (pkg.mSigningDetails.checkCapability(
17377                                        sourcePackageSetting.signatures.mSigningDetails,
17378                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17379
17380                            // the scanned package checks out, has signing certificate rotation
17381                            // history, and is newer; bring it over
17382                            sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails;
17383                            sigsOk = true;
17384                        } else {
17385                            sigsOk = false;
17386                        }
17387                    }
17388                    if (!sigsOk) {
17389                        // If the owning package is the system itself, we log but allow
17390                        // install to proceed; we fail the install on all other permission
17391                        // redefinitions.
17392                        if (!sourcePackageName.equals("android")) {
17393                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17394                                    + pkg.packageName + " attempting to redeclare permission "
17395                                    + perm.info.name + " already owned by " + sourcePackageName);
17396                            res.origPermission = perm.info.name;
17397                            res.origPackage = sourcePackageName;
17398                            return;
17399                        } else {
17400                            Slog.w(TAG, "Package " + pkg.packageName
17401                                    + " attempting to redeclare system permission "
17402                                    + perm.info.name + "; ignoring new declaration");
17403                            pkg.permissions.remove(i);
17404                        }
17405                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17406                        // Prevent apps to change protection level to dangerous from any other
17407                        // type as this would allow a privilege escalation where an app adds a
17408                        // normal/signature permission in other app's group and later redefines
17409                        // it as dangerous leading to the group auto-grant.
17410                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17411                                == PermissionInfo.PROTECTION_DANGEROUS) {
17412                            if (bp != null && !bp.isRuntime()) {
17413                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17414                                        + "non-runtime permission " + perm.info.name
17415                                        + " to runtime; keeping old protection level");
17416                                perm.info.protectionLevel = bp.getProtectionLevel();
17417                            }
17418                        }
17419                    }
17420                }
17421            }
17422        }
17423
17424        if (systemApp) {
17425            if (onExternal) {
17426                // Abort update; system app can't be replaced with app on sdcard
17427                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17428                        "Cannot install updates to system apps on sdcard");
17429                return;
17430            } else if (instantApp) {
17431                // Abort update; system app can't be replaced with an instant app
17432                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17433                        "Cannot update a system app with an instant app");
17434                return;
17435            }
17436        }
17437
17438        if (args.move != null) {
17439            // We did an in-place move, so dex is ready to roll
17440            scanFlags |= SCAN_NO_DEX;
17441            scanFlags |= SCAN_MOVE;
17442
17443            synchronized (mPackages) {
17444                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17445                if (ps == null) {
17446                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17447                            "Missing settings for moved package " + pkgName);
17448                }
17449
17450                // We moved the entire application as-is, so bring over the
17451                // previously derived ABI information.
17452                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17453                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17454            }
17455
17456        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17457            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17458            scanFlags |= SCAN_NO_DEX;
17459
17460            try {
17461                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17462                    args.abiOverride : pkg.cpuAbiOverride);
17463                final boolean extractNativeLibs = !pkg.isLibrary();
17464                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
17465            } catch (PackageManagerException pme) {
17466                Slog.e(TAG, "Error deriving application ABI", pme);
17467                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17468                return;
17469            }
17470
17471            // Shared libraries for the package need to be updated.
17472            synchronized (mPackages) {
17473                try {
17474                    updateSharedLibrariesLPr(pkg, null);
17475                } catch (PackageManagerException e) {
17476                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17477                }
17478            }
17479        }
17480
17481        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17482            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17483            return;
17484        }
17485
17486        if (PackageManagerServiceUtils.isApkVerityEnabled()) {
17487            String apkPath = null;
17488            synchronized (mPackages) {
17489                // Note that if the attacker managed to skip verify setup, for example by tampering
17490                // with the package settings, upon reboot we will do full apk verification when
17491                // verity is not detected.
17492                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17493                if (ps != null && ps.isPrivileged()) {
17494                    apkPath = pkg.baseCodePath;
17495                }
17496            }
17497
17498            if (apkPath != null) {
17499                final VerityUtils.SetupResult result =
17500                        VerityUtils.generateApkVeritySetupData(apkPath);
17501                if (result.isOk()) {
17502                    if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath);
17503                    FileDescriptor fd = result.getUnownedFileDescriptor();
17504                    try {
17505                        final byte[] signedRootHash = VerityUtils.generateFsverityRootHash(apkPath);
17506                        mInstaller.installApkVerity(apkPath, fd, result.getContentSize());
17507                        mInstaller.assertFsverityRootHashMatches(apkPath, signedRootHash);
17508                    } catch (InstallerException | IOException | DigestException |
17509                             NoSuchAlgorithmException e) {
17510                        res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17511                                "Failed to set up verity: " + e);
17512                        return;
17513                    } finally {
17514                        IoUtils.closeQuietly(fd);
17515                    }
17516                } else if (result.isFailed()) {
17517                    res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity");
17518                    return;
17519                } else {
17520                    // Do nothing if verity is skipped. Will fall back to full apk verification on
17521                    // reboot.
17522                }
17523            }
17524        }
17525
17526        if (!instantApp) {
17527            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17528        } else {
17529            if (DEBUG_DOMAIN_VERIFICATION) {
17530                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17531            }
17532        }
17533
17534        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17535                "installPackageLI")) {
17536            if (replace) {
17537                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17538                    // Static libs have a synthetic package name containing the version
17539                    // and cannot be updated as an update would get a new package name,
17540                    // unless this is the exact same version code which is useful for
17541                    // development.
17542                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17543                    if (existingPkg != null &&
17544                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
17545                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17546                                + "static-shared libs cannot be updated");
17547                        return;
17548                    }
17549                }
17550                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
17551                        installerPackageName, res, args.installReason);
17552            } else {
17553                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17554                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17555            }
17556        }
17557
17558        // Prepare the application profiles for the new code paths.
17559        // This needs to be done before invoking dexopt so that any install-time profile
17560        // can be used for optimizations.
17561        mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier()));
17562
17563        // Check whether we need to dexopt the app.
17564        //
17565        // NOTE: it is IMPORTANT to call dexopt:
17566        //   - after doRename which will sync the package data from PackageParser.Package and its
17567        //     corresponding ApplicationInfo.
17568        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
17569        //     uid of the application (pkg.applicationInfo.uid).
17570        //     This update happens in place!
17571        //
17572        // We only need to dexopt if the package meets ALL of the following conditions:
17573        //   1) it is not forward locked.
17574        //   2) it is not on on an external ASEC container.
17575        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17576        //   4) it is not debuggable.
17577        //
17578        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17579        // complete, so we skip this step during installation. Instead, we'll take extra time
17580        // the first time the instant app starts. It's preferred to do it this way to provide
17581        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17582        // middle of running an instant app. The default behaviour can be overridden
17583        // via gservices.
17584        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
17585                && !forwardLocked
17586                && !pkg.applicationInfo.isExternalAsec()
17587                && (!instantApp || Global.getInt(mContext.getContentResolver(),
17588                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0)
17589                && ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0);
17590
17591        if (performDexopt) {
17592            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17593            // Do not run PackageDexOptimizer through the local performDexOpt
17594            // method because `pkg` may not be in `mPackages` yet.
17595            //
17596            // Also, don't fail application installs if the dexopt step fails.
17597            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17598                    REASON_INSTALL,
17599                    DexoptOptions.DEXOPT_BOOT_COMPLETE |
17600                    DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE);
17601            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17602                    null /* instructionSets */,
17603                    getOrCreateCompilerPackageStats(pkg),
17604                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17605                    dexoptOptions);
17606            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17607        }
17608
17609        // Notify BackgroundDexOptService that the package has been changed.
17610        // If this is an update of a package which used to fail to compile,
17611        // BackgroundDexOptService will remove it from its blacklist.
17612        // TODO: Layering violation
17613        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17614
17615        synchronized (mPackages) {
17616            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17617            if (ps != null) {
17618                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17619                ps.setUpdateAvailable(false /*updateAvailable*/);
17620            }
17621
17622            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17623            for (int i = 0; i < childCount; i++) {
17624                PackageParser.Package childPkg = pkg.childPackages.get(i);
17625                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17626                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17627                if (childPs != null) {
17628                    childRes.newUsers = childPs.queryInstalledUsers(
17629                            sUserManager.getUserIds(), true);
17630                }
17631            }
17632
17633            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17634                updateSequenceNumberLP(ps, res.newUsers);
17635                updateInstantAppInstallerLocked(pkgName);
17636            }
17637        }
17638    }
17639
17640    private void startIntentFilterVerifications(int userId, boolean replacing,
17641            PackageParser.Package pkg) {
17642        if (mIntentFilterVerifierComponent == null) {
17643            Slog.w(TAG, "No IntentFilter verification will not be done as "
17644                    + "there is no IntentFilterVerifier available!");
17645            return;
17646        }
17647
17648        final int verifierUid = getPackageUid(
17649                mIntentFilterVerifierComponent.getPackageName(),
17650                MATCH_DEBUG_TRIAGED_MISSING,
17651                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17652
17653        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17654        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17655        mHandler.sendMessage(msg);
17656
17657        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17658        for (int i = 0; i < childCount; i++) {
17659            PackageParser.Package childPkg = pkg.childPackages.get(i);
17660            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17661            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17662            mHandler.sendMessage(msg);
17663        }
17664    }
17665
17666    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17667            PackageParser.Package pkg) {
17668        int size = pkg.activities.size();
17669        if (size == 0) {
17670            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17671                    "No activity, so no need to verify any IntentFilter!");
17672            return;
17673        }
17674
17675        final boolean hasDomainURLs = hasDomainURLs(pkg);
17676        if (!hasDomainURLs) {
17677            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17678                    "No domain URLs, so no need to verify any IntentFilter!");
17679            return;
17680        }
17681
17682        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17683                + " if any IntentFilter from the " + size
17684                + " Activities needs verification ...");
17685
17686        int count = 0;
17687        final String packageName = pkg.packageName;
17688
17689        synchronized (mPackages) {
17690            // If this is a new install and we see that we've already run verification for this
17691            // package, we have nothing to do: it means the state was restored from backup.
17692            if (!replacing) {
17693                IntentFilterVerificationInfo ivi =
17694                        mSettings.getIntentFilterVerificationLPr(packageName);
17695                if (ivi != null) {
17696                    if (DEBUG_DOMAIN_VERIFICATION) {
17697                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17698                                + ivi.getStatusString());
17699                    }
17700                    return;
17701                }
17702            }
17703
17704            // If any filters need to be verified, then all need to be.
17705            boolean needToVerify = false;
17706            for (PackageParser.Activity a : pkg.activities) {
17707                for (ActivityIntentInfo filter : a.intents) {
17708                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17709                        if (DEBUG_DOMAIN_VERIFICATION) {
17710                            Slog.d(TAG,
17711                                    "Intent filter needs verification, so processing all filters");
17712                        }
17713                        needToVerify = true;
17714                        break;
17715                    }
17716                }
17717            }
17718
17719            if (needToVerify) {
17720                final int verificationId = mIntentFilterVerificationToken++;
17721                for (PackageParser.Activity a : pkg.activities) {
17722                    for (ActivityIntentInfo filter : a.intents) {
17723                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17724                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17725                                    "Verification needed for IntentFilter:" + filter.toString());
17726                            mIntentFilterVerifier.addOneIntentFilterVerification(
17727                                    verifierUid, userId, verificationId, filter, packageName);
17728                            count++;
17729                        }
17730                    }
17731                }
17732            }
17733        }
17734
17735        if (count > 0) {
17736            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17737                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17738                    +  " for userId:" + userId);
17739            mIntentFilterVerifier.startVerifications(userId);
17740        } else {
17741            if (DEBUG_DOMAIN_VERIFICATION) {
17742                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17743            }
17744        }
17745    }
17746
17747    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17748        final ComponentName cn  = filter.activity.getComponentName();
17749        final String packageName = cn.getPackageName();
17750
17751        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17752                packageName);
17753        if (ivi == null) {
17754            return true;
17755        }
17756        int status = ivi.getStatus();
17757        switch (status) {
17758            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17759            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17760                return true;
17761
17762            default:
17763                // Nothing to do
17764                return false;
17765        }
17766    }
17767
17768    private static boolean isMultiArch(ApplicationInfo info) {
17769        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17770    }
17771
17772    private static boolean isExternal(PackageParser.Package pkg) {
17773        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17774    }
17775
17776    private static boolean isExternal(PackageSetting ps) {
17777        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17778    }
17779
17780    private static boolean isSystemApp(PackageParser.Package pkg) {
17781        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17782    }
17783
17784    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17785        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17786    }
17787
17788    private static boolean isOemApp(PackageParser.Package pkg) {
17789        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17790    }
17791
17792    private static boolean isVendorApp(PackageParser.Package pkg) {
17793        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17794    }
17795
17796    private static boolean isProductApp(PackageParser.Package pkg) {
17797        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
17798    }
17799
17800    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17801        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17802    }
17803
17804    private static boolean isSystemApp(PackageSetting ps) {
17805        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17806    }
17807
17808    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17809        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17810    }
17811
17812    private int packageFlagsToInstallFlags(PackageSetting ps) {
17813        int installFlags = 0;
17814        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17815            // This existing package was an external ASEC install when we have
17816            // the external flag without a UUID
17817            installFlags |= PackageManager.INSTALL_EXTERNAL;
17818        }
17819        if (ps.isForwardLocked()) {
17820            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17821        }
17822        return installFlags;
17823    }
17824
17825    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17826        if (isExternal(pkg)) {
17827            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17828                return mSettings.getExternalVersion();
17829            } else {
17830                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17831            }
17832        } else {
17833            return mSettings.getInternalVersion();
17834        }
17835    }
17836
17837    private void deleteTempPackageFiles() {
17838        final FilenameFilter filter = new FilenameFilter() {
17839            public boolean accept(File dir, String name) {
17840                return name.startsWith("vmdl") && name.endsWith(".tmp");
17841            }
17842        };
17843        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17844            file.delete();
17845        }
17846    }
17847
17848    @Override
17849    public void deletePackageAsUser(String packageName, int versionCode,
17850            IPackageDeleteObserver observer, int userId, int flags) {
17851        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17852                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17853    }
17854
17855    @Override
17856    public void deletePackageVersioned(VersionedPackage versionedPackage,
17857            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17858        final int callingUid = Binder.getCallingUid();
17859        mContext.enforceCallingOrSelfPermission(
17860                android.Manifest.permission.DELETE_PACKAGES, null);
17861        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17862        Preconditions.checkNotNull(versionedPackage);
17863        Preconditions.checkNotNull(observer);
17864        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17865                PackageManager.VERSION_CODE_HIGHEST,
17866                Long.MAX_VALUE, "versionCode must be >= -1");
17867
17868        final String packageName = versionedPackage.getPackageName();
17869        final long versionCode = versionedPackage.getLongVersionCode();
17870        final String internalPackageName;
17871        synchronized (mPackages) {
17872            // Normalize package name to handle renamed packages and static libs
17873            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17874        }
17875
17876        final int uid = Binder.getCallingUid();
17877        if (!isOrphaned(internalPackageName)
17878                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17879            try {
17880                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17881                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17882                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17883                observer.onUserActionRequired(intent);
17884            } catch (RemoteException re) {
17885            }
17886            return;
17887        }
17888        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17889        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17890        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17891            mContext.enforceCallingOrSelfPermission(
17892                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17893                    "deletePackage for user " + userId);
17894        }
17895
17896        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17897            try {
17898                observer.onPackageDeleted(packageName,
17899                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17900            } catch (RemoteException re) {
17901            }
17902            return;
17903        }
17904
17905        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17906            try {
17907                observer.onPackageDeleted(packageName,
17908                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17909            } catch (RemoteException re) {
17910            }
17911            return;
17912        }
17913
17914        if (DEBUG_REMOVE) {
17915            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17916                    + " deleteAllUsers: " + deleteAllUsers + " version="
17917                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17918                    ? "VERSION_CODE_HIGHEST" : versionCode));
17919        }
17920        // Queue up an async operation since the package deletion may take a little while.
17921        mHandler.post(new Runnable() {
17922            public void run() {
17923                mHandler.removeCallbacks(this);
17924                int returnCode;
17925                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17926                boolean doDeletePackage = true;
17927                if (ps != null) {
17928                    final boolean targetIsInstantApp =
17929                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17930                    doDeletePackage = !targetIsInstantApp
17931                            || canViewInstantApps;
17932                }
17933                if (doDeletePackage) {
17934                    if (!deleteAllUsers) {
17935                        returnCode = deletePackageX(internalPackageName, versionCode,
17936                                userId, deleteFlags);
17937                    } else {
17938                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17939                                internalPackageName, users);
17940                        // If nobody is blocking uninstall, proceed with delete for all users
17941                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17942                            returnCode = deletePackageX(internalPackageName, versionCode,
17943                                    userId, deleteFlags);
17944                        } else {
17945                            // Otherwise uninstall individually for users with blockUninstalls=false
17946                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17947                            for (int userId : users) {
17948                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17949                                    returnCode = deletePackageX(internalPackageName, versionCode,
17950                                            userId, userFlags);
17951                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17952                                        Slog.w(TAG, "Package delete failed for user " + userId
17953                                                + ", returnCode " + returnCode);
17954                                    }
17955                                }
17956                            }
17957                            // The app has only been marked uninstalled for certain users.
17958                            // We still need to report that delete was blocked
17959                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17960                        }
17961                    }
17962                } else {
17963                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17964                }
17965                try {
17966                    observer.onPackageDeleted(packageName, returnCode, null);
17967                } catch (RemoteException e) {
17968                    Log.i(TAG, "Observer no longer exists.");
17969                } //end catch
17970            } //end run
17971        });
17972    }
17973
17974    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17975        if (pkg.staticSharedLibName != null) {
17976            return pkg.manifestPackageName;
17977        }
17978        return pkg.packageName;
17979    }
17980
17981    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17982        // Handle renamed packages
17983        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17984        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17985
17986        // Is this a static library?
17987        LongSparseArray<SharedLibraryEntry> versionedLib =
17988                mStaticLibsByDeclaringPackage.get(packageName);
17989        if (versionedLib == null || versionedLib.size() <= 0) {
17990            return packageName;
17991        }
17992
17993        // Figure out which lib versions the caller can see
17994        LongSparseLongArray versionsCallerCanSee = null;
17995        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17996        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17997                && callingAppId != Process.ROOT_UID) {
17998            versionsCallerCanSee = new LongSparseLongArray();
17999            String libName = versionedLib.valueAt(0).info.getName();
18000            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18001            if (uidPackages != null) {
18002                for (String uidPackage : uidPackages) {
18003                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18004                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18005                    if (libIdx >= 0) {
18006                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
18007                        versionsCallerCanSee.append(libVersion, libVersion);
18008                    }
18009                }
18010            }
18011        }
18012
18013        // Caller can see nothing - done
18014        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18015            return packageName;
18016        }
18017
18018        // Find the version the caller can see and the app version code
18019        SharedLibraryEntry highestVersion = null;
18020        final int versionCount = versionedLib.size();
18021        for (int i = 0; i < versionCount; i++) {
18022            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18023            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18024                    libEntry.info.getLongVersion()) < 0) {
18025                continue;
18026            }
18027            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
18028            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18029                if (libVersionCode == versionCode) {
18030                    return libEntry.apk;
18031                }
18032            } else if (highestVersion == null) {
18033                highestVersion = libEntry;
18034            } else if (libVersionCode  > highestVersion.info
18035                    .getDeclaringPackage().getLongVersionCode()) {
18036                highestVersion = libEntry;
18037            }
18038        }
18039
18040        if (highestVersion != null) {
18041            return highestVersion.apk;
18042        }
18043
18044        return packageName;
18045    }
18046
18047    boolean isCallerVerifier(int callingUid) {
18048        final int callingUserId = UserHandle.getUserId(callingUid);
18049        return mRequiredVerifierPackage != null &&
18050                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
18051    }
18052
18053    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18054        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18055              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18056            return true;
18057        }
18058        final int callingUserId = UserHandle.getUserId(callingUid);
18059        // If the caller installed the pkgName, then allow it to silently uninstall.
18060        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18061            return true;
18062        }
18063
18064        // Allow package verifier to silently uninstall.
18065        if (mRequiredVerifierPackage != null &&
18066                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18067            return true;
18068        }
18069
18070        // Allow package uninstaller to silently uninstall.
18071        if (mRequiredUninstallerPackage != null &&
18072                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18073            return true;
18074        }
18075
18076        // Allow storage manager to silently uninstall.
18077        if (mStorageManagerPackage != null &&
18078                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18079            return true;
18080        }
18081
18082        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
18083        // uninstall for device owner provisioning.
18084        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
18085                == PERMISSION_GRANTED) {
18086            return true;
18087        }
18088
18089        return false;
18090    }
18091
18092    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18093        int[] result = EMPTY_INT_ARRAY;
18094        for (int userId : userIds) {
18095            if (getBlockUninstallForUser(packageName, userId)) {
18096                result = ArrayUtils.appendInt(result, userId);
18097            }
18098        }
18099        return result;
18100    }
18101
18102    @Override
18103    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18104        final int callingUid = Binder.getCallingUid();
18105        if (getInstantAppPackageName(callingUid) != null
18106                && !isCallerSameApp(packageName, callingUid)) {
18107            return false;
18108        }
18109        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18110    }
18111
18112    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18113        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18114                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18115        try {
18116            if (dpm != null) {
18117                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18118                        /* callingUserOnly =*/ false);
18119                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18120                        : deviceOwnerComponentName.getPackageName();
18121                // Does the package contains the device owner?
18122                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18123                // this check is probably not needed, since DO should be registered as a device
18124                // admin on some user too. (Original bug for this: b/17657954)
18125                if (packageName.equals(deviceOwnerPackageName)) {
18126                    return true;
18127                }
18128                // Does it contain a device admin for any user?
18129                int[] users;
18130                if (userId == UserHandle.USER_ALL) {
18131                    users = sUserManager.getUserIds();
18132                } else {
18133                    users = new int[]{userId};
18134                }
18135                for (int i = 0; i < users.length; ++i) {
18136                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18137                        return true;
18138                    }
18139                }
18140            }
18141        } catch (RemoteException e) {
18142        }
18143        return false;
18144    }
18145
18146    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18147        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18148    }
18149
18150    /**
18151     *  This method is an internal method that could be get invoked either
18152     *  to delete an installed package or to clean up a failed installation.
18153     *  After deleting an installed package, a broadcast is sent to notify any
18154     *  listeners that the package has been removed. For cleaning up a failed
18155     *  installation, the broadcast is not necessary since the package's
18156     *  installation wouldn't have sent the initial broadcast either
18157     *  The key steps in deleting a package are
18158     *  deleting the package information in internal structures like mPackages,
18159     *  deleting the packages base directories through installd
18160     *  updating mSettings to reflect current status
18161     *  persisting settings for later use
18162     *  sending a broadcast if necessary
18163     */
18164    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
18165        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18166        final boolean res;
18167
18168        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18169                ? UserHandle.USER_ALL : userId;
18170
18171        if (isPackageDeviceAdmin(packageName, removeUser)) {
18172            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18173            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18174        }
18175
18176        PackageSetting uninstalledPs = null;
18177        PackageParser.Package pkg = null;
18178
18179        // for the uninstall-updates case and restricted profiles, remember the per-
18180        // user handle installed state
18181        int[] allUsers;
18182        synchronized (mPackages) {
18183            uninstalledPs = mSettings.mPackages.get(packageName);
18184            if (uninstalledPs == null) {
18185                Slog.w(TAG, "Not removing non-existent package " + packageName);
18186                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18187            }
18188
18189            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18190                    && uninstalledPs.versionCode != versionCode) {
18191                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18192                        + uninstalledPs.versionCode + " != " + versionCode);
18193                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18194            }
18195
18196            // Static shared libs can be declared by any package, so let us not
18197            // allow removing a package if it provides a lib others depend on.
18198            pkg = mPackages.get(packageName);
18199
18200            allUsers = sUserManager.getUserIds();
18201
18202            if (pkg != null && pkg.staticSharedLibName != null) {
18203                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18204                        pkg.staticSharedLibVersion);
18205                if (libEntry != null) {
18206                    for (int currUserId : allUsers) {
18207                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18208                            continue;
18209                        }
18210                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18211                                libEntry.info, 0, currUserId);
18212                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18213                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18214                                    + " hosting lib " + libEntry.info.getName() + " version "
18215                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
18216                                    + " for user " + currUserId);
18217                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18218                        }
18219                    }
18220                }
18221            }
18222
18223            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18224        }
18225
18226        final int freezeUser;
18227        if (isUpdatedSystemApp(uninstalledPs)
18228                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18229            // We're downgrading a system app, which will apply to all users, so
18230            // freeze them all during the downgrade
18231            freezeUser = UserHandle.USER_ALL;
18232        } else {
18233            freezeUser = removeUser;
18234        }
18235
18236        synchronized (mInstallLock) {
18237            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18238            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18239                    deleteFlags, "deletePackageX")) {
18240                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18241                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
18242            }
18243            synchronized (mPackages) {
18244                if (res) {
18245                    if (pkg != null) {
18246                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18247                    }
18248                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18249                    updateInstantAppInstallerLocked(packageName);
18250                }
18251            }
18252        }
18253
18254        if (res) {
18255            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18256            info.sendPackageRemovedBroadcasts(killApp);
18257            info.sendSystemPackageUpdatedBroadcasts();
18258            info.sendSystemPackageAppearedBroadcasts();
18259        }
18260        // Force a gc here.
18261        Runtime.getRuntime().gc();
18262        // Delete the resources here after sending the broadcast to let
18263        // other processes clean up before deleting resources.
18264        if (info.args != null) {
18265            synchronized (mInstallLock) {
18266                info.args.doPostDeleteLI(true);
18267            }
18268        }
18269
18270        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18271    }
18272
18273    static class PackageRemovedInfo {
18274        final PackageSender packageSender;
18275        String removedPackage;
18276        String installerPackageName;
18277        int uid = -1;
18278        int removedAppId = -1;
18279        int[] origUsers;
18280        int[] removedUsers = null;
18281        int[] broadcastUsers = null;
18282        int[] instantUserIds = null;
18283        SparseArray<Integer> installReasons;
18284        boolean isRemovedPackageSystemUpdate = false;
18285        boolean isUpdate;
18286        boolean dataRemoved;
18287        boolean removedForAllUsers;
18288        boolean isStaticSharedLib;
18289        // Clean up resources deleted packages.
18290        InstallArgs args = null;
18291        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18292        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18293
18294        PackageRemovedInfo(PackageSender packageSender) {
18295            this.packageSender = packageSender;
18296        }
18297
18298        void sendPackageRemovedBroadcasts(boolean killApp) {
18299            sendPackageRemovedBroadcastInternal(killApp);
18300            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18301            for (int i = 0; i < childCount; i++) {
18302                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18303                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18304            }
18305        }
18306
18307        void sendSystemPackageUpdatedBroadcasts() {
18308            if (isRemovedPackageSystemUpdate) {
18309                sendSystemPackageUpdatedBroadcastsInternal();
18310                final int childCount = (removedChildPackages != null)
18311                        ? removedChildPackages.size() : 0;
18312                for (int i = 0; i < childCount; i++) {
18313                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18314                    if (childInfo.isRemovedPackageSystemUpdate) {
18315                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18316                    }
18317                }
18318            }
18319        }
18320
18321        void sendSystemPackageAppearedBroadcasts() {
18322            final int packageCount = (appearedChildPackages != null)
18323                    ? appearedChildPackages.size() : 0;
18324            for (int i = 0; i < packageCount; i++) {
18325                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18326                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18327                    true /*sendBootCompleted*/, false /*startReceiver*/,
18328                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
18329            }
18330        }
18331
18332        private void sendSystemPackageUpdatedBroadcastsInternal() {
18333            Bundle extras = new Bundle(2);
18334            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18335            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18336            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18337                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18338            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18339                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18340            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18341                null, null, 0, removedPackage, null, null, null);
18342            if (installerPackageName != null) {
18343                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18344                        removedPackage, extras, 0 /*flags*/,
18345                        installerPackageName, null, null, null);
18346                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18347                        removedPackage, extras, 0 /*flags*/,
18348                        installerPackageName, null, null, null);
18349            }
18350        }
18351
18352        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18353            // Don't send static shared library removal broadcasts as these
18354            // libs are visible only the the apps that depend on them an one
18355            // cannot remove the library if it has a dependency.
18356            if (isStaticSharedLib) {
18357                return;
18358            }
18359            Bundle extras = new Bundle(2);
18360            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18361            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18362            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18363            if (isUpdate || isRemovedPackageSystemUpdate) {
18364                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18365            }
18366            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18367            if (removedPackage != null) {
18368                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18369                    removedPackage, extras, 0, null /*targetPackage*/, null,
18370                    broadcastUsers, instantUserIds);
18371                if (installerPackageName != null) {
18372                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18373                            removedPackage, extras, 0 /*flags*/,
18374                            installerPackageName, null, broadcastUsers, instantUserIds);
18375                }
18376                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18377                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18378                        removedPackage, extras,
18379                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18380                        null, null, broadcastUsers, instantUserIds);
18381                    packageSender.notifyPackageRemoved(removedPackage);
18382                }
18383            }
18384            if (removedAppId >= 0) {
18385                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18386                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18387                    null, null, broadcastUsers, instantUserIds);
18388            }
18389        }
18390
18391        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18392            removedUsers = userIds;
18393            if (removedUsers == null) {
18394                broadcastUsers = null;
18395                return;
18396            }
18397
18398            broadcastUsers = EMPTY_INT_ARRAY;
18399            instantUserIds = EMPTY_INT_ARRAY;
18400            for (int i = userIds.length - 1; i >= 0; --i) {
18401                final int userId = userIds[i];
18402                if (deletedPackageSetting.getInstantApp(userId)) {
18403                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
18404                } else {
18405                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18406                }
18407            }
18408        }
18409    }
18410
18411    /*
18412     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18413     * flag is not set, the data directory is removed as well.
18414     * make sure this flag is set for partially installed apps. If not its meaningless to
18415     * delete a partially installed application.
18416     */
18417    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18418            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18419        String packageName = ps.name;
18420        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18421        // Retrieve object to delete permissions for shared user later on
18422        final PackageParser.Package deletedPkg;
18423        final PackageSetting deletedPs;
18424        // reader
18425        synchronized (mPackages) {
18426            deletedPkg = mPackages.get(packageName);
18427            deletedPs = mSettings.mPackages.get(packageName);
18428            if (outInfo != null) {
18429                outInfo.removedPackage = packageName;
18430                outInfo.installerPackageName = ps.installerPackageName;
18431                outInfo.isStaticSharedLib = deletedPkg != null
18432                        && deletedPkg.staticSharedLibName != null;
18433                outInfo.populateUsers(deletedPs == null ? null
18434                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18435            }
18436        }
18437
18438        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
18439
18440        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18441            final PackageParser.Package resolvedPkg;
18442            if (deletedPkg != null) {
18443                resolvedPkg = deletedPkg;
18444            } else {
18445                // We don't have a parsed package when it lives on an ejected
18446                // adopted storage device, so fake something together
18447                resolvedPkg = new PackageParser.Package(ps.name);
18448                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18449            }
18450            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18451                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18452            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18453            if (outInfo != null) {
18454                outInfo.dataRemoved = true;
18455            }
18456            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18457        }
18458
18459        int removedAppId = -1;
18460
18461        // writer
18462        synchronized (mPackages) {
18463            boolean installedStateChanged = false;
18464            if (deletedPs != null) {
18465                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18466                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18467                    clearDefaultBrowserIfNeeded(packageName);
18468                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18469                    removedAppId = mSettings.removePackageLPw(packageName);
18470                    if (outInfo != null) {
18471                        outInfo.removedAppId = removedAppId;
18472                    }
18473                    mPermissionManager.updatePermissions(
18474                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
18475                    if (deletedPs.sharedUser != null) {
18476                        // Remove permissions associated with package. Since runtime
18477                        // permissions are per user we have to kill the removed package
18478                        // or packages running under the shared user of the removed
18479                        // package if revoking the permissions requested only by the removed
18480                        // package is successful and this causes a change in gids.
18481                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18482                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18483                                    userId);
18484                            if (userIdToKill == UserHandle.USER_ALL
18485                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18486                                // If gids changed for this user, kill all affected packages.
18487                                mHandler.post(new Runnable() {
18488                                    @Override
18489                                    public void run() {
18490                                        // This has to happen with no lock held.
18491                                        killApplication(deletedPs.name, deletedPs.appId,
18492                                                KILL_APP_REASON_GIDS_CHANGED);
18493                                    }
18494                                });
18495                                break;
18496                            }
18497                        }
18498                    }
18499                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18500                }
18501                // make sure to preserve per-user disabled state if this removal was just
18502                // a downgrade of a system app to the factory package
18503                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18504                    if (DEBUG_REMOVE) {
18505                        Slog.d(TAG, "Propagating install state across downgrade");
18506                    }
18507                    for (int userId : allUserHandles) {
18508                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18509                        if (DEBUG_REMOVE) {
18510                            Slog.d(TAG, "    user " + userId + " => " + installed);
18511                        }
18512                        if (installed != ps.getInstalled(userId)) {
18513                            installedStateChanged = true;
18514                        }
18515                        ps.setInstalled(installed, userId);
18516                    }
18517                }
18518            }
18519            // can downgrade to reader
18520            if (writeSettings) {
18521                // Save settings now
18522                mSettings.writeLPr();
18523            }
18524            if (installedStateChanged) {
18525                mSettings.writeKernelMappingLPr(ps);
18526            }
18527        }
18528        if (removedAppId != -1) {
18529            // A user ID was deleted here. Go through all users and remove it
18530            // from KeyStore.
18531            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18532        }
18533    }
18534
18535    static boolean locationIsPrivileged(String path) {
18536        try {
18537            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
18538            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
18539            final File privilegedOdmAppDir = new File(Environment.getOdmDirectory(), "priv-app");
18540            final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
18541            return path.startsWith(privilegedAppDir.getCanonicalPath())
18542                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath())
18543                    || path.startsWith(privilegedOdmAppDir.getCanonicalPath())
18544                    || path.startsWith(privilegedProductAppDir.getCanonicalPath());
18545        } catch (IOException e) {
18546            Slog.e(TAG, "Unable to access code path " + path);
18547        }
18548        return false;
18549    }
18550
18551    static boolean locationIsOem(String path) {
18552        try {
18553            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
18554        } catch (IOException e) {
18555            Slog.e(TAG, "Unable to access code path " + path);
18556        }
18557        return false;
18558    }
18559
18560    static boolean locationIsVendor(String path) {
18561        try {
18562            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath())
18563                    || path.startsWith(Environment.getOdmDirectory().getCanonicalPath());
18564        } catch (IOException e) {
18565            Slog.e(TAG, "Unable to access code path " + path);
18566        }
18567        return false;
18568    }
18569
18570    static boolean locationIsProduct(String path) {
18571        try {
18572            return path.startsWith(Environment.getProductDirectory().getCanonicalPath());
18573        } catch (IOException e) {
18574            Slog.e(TAG, "Unable to access code path " + path);
18575        }
18576        return false;
18577    }
18578
18579    /*
18580     * Tries to delete system package.
18581     */
18582    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18583            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18584            boolean writeSettings) {
18585        if (deletedPs.parentPackageName != null) {
18586            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18587            return false;
18588        }
18589
18590        final boolean applyUserRestrictions
18591                = (allUserHandles != null) && (outInfo.origUsers != null);
18592        final PackageSetting disabledPs;
18593        // Confirm if the system package has been updated
18594        // An updated system app can be deleted. This will also have to restore
18595        // the system pkg from system partition
18596        // reader
18597        synchronized (mPackages) {
18598            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18599        }
18600
18601        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18602                + " disabledPs=" + disabledPs);
18603
18604        if (disabledPs == null) {
18605            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18606            return false;
18607        } else if (DEBUG_REMOVE) {
18608            Slog.d(TAG, "Deleting system pkg from data partition");
18609        }
18610
18611        if (DEBUG_REMOVE) {
18612            if (applyUserRestrictions) {
18613                Slog.d(TAG, "Remembering install states:");
18614                for (int userId : allUserHandles) {
18615                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18616                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18617                }
18618            }
18619        }
18620
18621        // Delete the updated package
18622        outInfo.isRemovedPackageSystemUpdate = true;
18623        if (outInfo.removedChildPackages != null) {
18624            final int childCount = (deletedPs.childPackageNames != null)
18625                    ? deletedPs.childPackageNames.size() : 0;
18626            for (int i = 0; i < childCount; i++) {
18627                String childPackageName = deletedPs.childPackageNames.get(i);
18628                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18629                        .contains(childPackageName)) {
18630                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18631                            childPackageName);
18632                    if (childInfo != null) {
18633                        childInfo.isRemovedPackageSystemUpdate = true;
18634                    }
18635                }
18636            }
18637        }
18638
18639        if (disabledPs.versionCode < deletedPs.versionCode) {
18640            // Delete data for downgrades
18641            flags &= ~PackageManager.DELETE_KEEP_DATA;
18642        } else {
18643            // Preserve data by setting flag
18644            flags |= PackageManager.DELETE_KEEP_DATA;
18645        }
18646
18647        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18648                outInfo, writeSettings, disabledPs.pkg);
18649        if (!ret) {
18650            return false;
18651        }
18652
18653        // writer
18654        synchronized (mPackages) {
18655            // NOTE: The system package always needs to be enabled; even if it's for
18656            // a compressed stub. If we don't, installing the system package fails
18657            // during scan [scanning checks the disabled packages]. We will reverse
18658            // this later, after we've "installed" the stub.
18659            // Reinstate the old system package
18660            enableSystemPackageLPw(disabledPs.pkg);
18661            // Remove any native libraries from the upgraded package.
18662            removeNativeBinariesLI(deletedPs);
18663        }
18664
18665        // Install the system package
18666        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18667        try {
18668            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
18669                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18670        } catch (PackageManagerException e) {
18671            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18672                    + e.getMessage());
18673            return false;
18674        } finally {
18675            if (disabledPs.pkg.isStub) {
18676                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18677            }
18678        }
18679        return true;
18680    }
18681
18682    /**
18683     * Installs a package that's already on the system partition.
18684     */
18685    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
18686            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18687            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18688                    throws PackageManagerException {
18689        @ParseFlags int parseFlags =
18690                mDefParseFlags
18691                | PackageParser.PARSE_MUST_BE_APK
18692                | PackageParser.PARSE_IS_SYSTEM_DIR;
18693        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
18694        if (isPrivileged || locationIsPrivileged(codePathString)) {
18695            scanFlags |= SCAN_AS_PRIVILEGED;
18696        }
18697        if (locationIsOem(codePathString)) {
18698            scanFlags |= SCAN_AS_OEM;
18699        }
18700        if (locationIsVendor(codePathString)) {
18701            scanFlags |= SCAN_AS_VENDOR;
18702        }
18703        if (locationIsProduct(codePathString)) {
18704            scanFlags |= SCAN_AS_PRODUCT;
18705        }
18706
18707        final File codePath = new File(codePathString);
18708        final PackageParser.Package pkg =
18709                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
18710
18711        try {
18712            // update shared libraries for the newly re-installed system package
18713            updateSharedLibrariesLPr(pkg, null);
18714        } catch (PackageManagerException e) {
18715            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18716        }
18717
18718        prepareAppDataAfterInstallLIF(pkg);
18719
18720        // writer
18721        synchronized (mPackages) {
18722            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18723
18724            // Propagate the permissions state as we do not want to drop on the floor
18725            // runtime permissions. The update permissions method below will take
18726            // care of removing obsolete permissions and grant install permissions.
18727            if (origPermissionState != null) {
18728                ps.getPermissionsState().copyFrom(origPermissionState);
18729            }
18730            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18731                    mPermissionCallback);
18732
18733            final boolean applyUserRestrictions
18734                    = (allUserHandles != null) && (origUserHandles != null);
18735            if (applyUserRestrictions) {
18736                boolean installedStateChanged = false;
18737                if (DEBUG_REMOVE) {
18738                    Slog.d(TAG, "Propagating install state across reinstall");
18739                }
18740                for (int userId : allUserHandles) {
18741                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18742                    if (DEBUG_REMOVE) {
18743                        Slog.d(TAG, "    user " + userId + " => " + installed);
18744                    }
18745                    if (installed != ps.getInstalled(userId)) {
18746                        installedStateChanged = true;
18747                    }
18748                    ps.setInstalled(installed, userId);
18749
18750                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18751                }
18752                // Regardless of writeSettings we need to ensure that this restriction
18753                // state propagation is persisted
18754                mSettings.writeAllUsersPackageRestrictionsLPr();
18755                if (installedStateChanged) {
18756                    mSettings.writeKernelMappingLPr(ps);
18757                }
18758            }
18759            // can downgrade to reader here
18760            if (writeSettings) {
18761                mSettings.writeLPr();
18762            }
18763        }
18764        return pkg;
18765    }
18766
18767    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18768            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18769            PackageRemovedInfo outInfo, boolean writeSettings,
18770            PackageParser.Package replacingPackage) {
18771        synchronized (mPackages) {
18772            if (outInfo != null) {
18773                outInfo.uid = ps.appId;
18774            }
18775
18776            if (outInfo != null && outInfo.removedChildPackages != null) {
18777                final int childCount = (ps.childPackageNames != null)
18778                        ? ps.childPackageNames.size() : 0;
18779                for (int i = 0; i < childCount; i++) {
18780                    String childPackageName = ps.childPackageNames.get(i);
18781                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18782                    if (childPs == null) {
18783                        return false;
18784                    }
18785                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18786                            childPackageName);
18787                    if (childInfo != null) {
18788                        childInfo.uid = childPs.appId;
18789                    }
18790                }
18791            }
18792        }
18793
18794        // Delete package data from internal structures and also remove data if flag is set
18795        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18796
18797        // Delete the child packages data
18798        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18799        for (int i = 0; i < childCount; i++) {
18800            PackageSetting childPs;
18801            synchronized (mPackages) {
18802                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18803            }
18804            if (childPs != null) {
18805                PackageRemovedInfo childOutInfo = (outInfo != null
18806                        && outInfo.removedChildPackages != null)
18807                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18808                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18809                        && (replacingPackage != null
18810                        && !replacingPackage.hasChildPackage(childPs.name))
18811                        ? flags & ~DELETE_KEEP_DATA : flags;
18812                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18813                        deleteFlags, writeSettings);
18814            }
18815        }
18816
18817        // Delete application code and resources only for parent packages
18818        if (ps.parentPackageName == null) {
18819            if (deleteCodeAndResources && (outInfo != null)) {
18820                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18821                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18822                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18823            }
18824        }
18825
18826        return true;
18827    }
18828
18829    @Override
18830    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18831            int userId) {
18832        mContext.enforceCallingOrSelfPermission(
18833                android.Manifest.permission.DELETE_PACKAGES, null);
18834        synchronized (mPackages) {
18835            // Cannot block uninstall of static shared libs as they are
18836            // considered a part of the using app (emulating static linking).
18837            // Also static libs are installed always on internal storage.
18838            PackageParser.Package pkg = mPackages.get(packageName);
18839            if (pkg != null && pkg.staticSharedLibName != null) {
18840                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18841                        + " providing static shared library: " + pkg.staticSharedLibName);
18842                return false;
18843            }
18844            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18845            mSettings.writePackageRestrictionsLPr(userId);
18846        }
18847        return true;
18848    }
18849
18850    @Override
18851    public boolean getBlockUninstallForUser(String packageName, int userId) {
18852        synchronized (mPackages) {
18853            final PackageSetting ps = mSettings.mPackages.get(packageName);
18854            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18855                return false;
18856            }
18857            return mSettings.getBlockUninstallLPr(userId, packageName);
18858        }
18859    }
18860
18861    @Override
18862    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18863        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18864        synchronized (mPackages) {
18865            PackageSetting ps = mSettings.mPackages.get(packageName);
18866            if (ps == null) {
18867                Log.w(TAG, "Package doesn't exist: " + packageName);
18868                return false;
18869            }
18870            if (systemUserApp) {
18871                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18872            } else {
18873                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18874            }
18875            mSettings.writeLPr();
18876        }
18877        return true;
18878    }
18879
18880    /*
18881     * This method handles package deletion in general
18882     */
18883    private boolean deletePackageLIF(String packageName, UserHandle user,
18884            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18885            PackageRemovedInfo outInfo, boolean writeSettings,
18886            PackageParser.Package replacingPackage) {
18887        if (packageName == null) {
18888            Slog.w(TAG, "Attempt to delete null packageName.");
18889            return false;
18890        }
18891
18892        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18893
18894        PackageSetting ps;
18895        synchronized (mPackages) {
18896            ps = mSettings.mPackages.get(packageName);
18897            if (ps == null) {
18898                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18899                return false;
18900            }
18901
18902            if (ps.parentPackageName != null && (!isSystemApp(ps)
18903                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18904                if (DEBUG_REMOVE) {
18905                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18906                            + ((user == null) ? UserHandle.USER_ALL : user));
18907                }
18908                final int removedUserId = (user != null) ? user.getIdentifier()
18909                        : UserHandle.USER_ALL;
18910
18911                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18912                    return false;
18913                }
18914                markPackageUninstalledForUserLPw(ps, user);
18915                scheduleWritePackageRestrictionsLocked(user);
18916                return true;
18917            }
18918        }
18919
18920        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
18921        if (ps.getPermissionsState().hasPermission(Manifest.permission.SUSPEND_APPS, userId)) {
18922            unsuspendForSuspendingPackage(packageName, userId);
18923        }
18924
18925
18926        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18927                && user.getIdentifier() != UserHandle.USER_ALL)) {
18928            // The caller is asking that the package only be deleted for a single
18929            // user.  To do this, we just mark its uninstalled state and delete
18930            // its data. If this is a system app, we only allow this to happen if
18931            // they have set the special DELETE_SYSTEM_APP which requests different
18932            // semantics than normal for uninstalling system apps.
18933            markPackageUninstalledForUserLPw(ps, user);
18934
18935            if (!isSystemApp(ps)) {
18936                // Do not uninstall the APK if an app should be cached
18937                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18938                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18939                    // Other user still have this package installed, so all
18940                    // we need to do is clear this user's data and save that
18941                    // it is uninstalled.
18942                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18943                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18944                        return false;
18945                    }
18946                    scheduleWritePackageRestrictionsLocked(user);
18947                    return true;
18948                } else {
18949                    // We need to set it back to 'installed' so the uninstall
18950                    // broadcasts will be sent correctly.
18951                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18952                    ps.setInstalled(true, user.getIdentifier());
18953                    mSettings.writeKernelMappingLPr(ps);
18954                }
18955            } else {
18956                // This is a system app, so we assume that the
18957                // other users still have this package installed, so all
18958                // we need to do is clear this user's data and save that
18959                // it is uninstalled.
18960                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18961                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18962                    return false;
18963                }
18964                scheduleWritePackageRestrictionsLocked(user);
18965                return true;
18966            }
18967        }
18968
18969        // If we are deleting a composite package for all users, keep track
18970        // of result for each child.
18971        if (ps.childPackageNames != null && outInfo != null) {
18972            synchronized (mPackages) {
18973                final int childCount = ps.childPackageNames.size();
18974                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18975                for (int i = 0; i < childCount; i++) {
18976                    String childPackageName = ps.childPackageNames.get(i);
18977                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18978                    childInfo.removedPackage = childPackageName;
18979                    childInfo.installerPackageName = ps.installerPackageName;
18980                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18981                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18982                    if (childPs != null) {
18983                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18984                    }
18985                }
18986            }
18987        }
18988
18989        boolean ret = false;
18990        if (isSystemApp(ps)) {
18991            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18992            // When an updated system application is deleted we delete the existing resources
18993            // as well and fall back to existing code in system partition
18994            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18995        } else {
18996            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18997            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18998                    outInfo, writeSettings, replacingPackage);
18999        }
19000
19001        // Take a note whether we deleted the package for all users
19002        if (outInfo != null) {
19003            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19004            if (outInfo.removedChildPackages != null) {
19005                synchronized (mPackages) {
19006                    final int childCount = outInfo.removedChildPackages.size();
19007                    for (int i = 0; i < childCount; i++) {
19008                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19009                        if (childInfo != null) {
19010                            childInfo.removedForAllUsers = mPackages.get(
19011                                    childInfo.removedPackage) == null;
19012                        }
19013                    }
19014                }
19015            }
19016            // If we uninstalled an update to a system app there may be some
19017            // child packages that appeared as they are declared in the system
19018            // app but were not declared in the update.
19019            if (isSystemApp(ps)) {
19020                synchronized (mPackages) {
19021                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19022                    final int childCount = (updatedPs.childPackageNames != null)
19023                            ? updatedPs.childPackageNames.size() : 0;
19024                    for (int i = 0; i < childCount; i++) {
19025                        String childPackageName = updatedPs.childPackageNames.get(i);
19026                        if (outInfo.removedChildPackages == null
19027                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19028                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19029                            if (childPs == null) {
19030                                continue;
19031                            }
19032                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19033                            installRes.name = childPackageName;
19034                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19035                            installRes.pkg = mPackages.get(childPackageName);
19036                            installRes.uid = childPs.pkg.applicationInfo.uid;
19037                            if (outInfo.appearedChildPackages == null) {
19038                                outInfo.appearedChildPackages = new ArrayMap<>();
19039                            }
19040                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19041                        }
19042                    }
19043                }
19044            }
19045        }
19046
19047        return ret;
19048    }
19049
19050    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19051        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19052                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19053        for (int nextUserId : userIds) {
19054            if (DEBUG_REMOVE) {
19055                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19056            }
19057            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19058                    false /*installed*/,
19059                    true /*stopped*/,
19060                    true /*notLaunched*/,
19061                    false /*hidden*/,
19062                    false /*suspended*/,
19063                    null /*suspendingPackage*/,
19064                    null /*dialogMessage*/,
19065                    null /*suspendedAppExtras*/,
19066                    null /*suspendedLauncherExtras*/,
19067                    false /*instantApp*/,
19068                    false /*virtualPreload*/,
19069                    null /*lastDisableAppCaller*/,
19070                    null /*enabledComponents*/,
19071                    null /*disabledComponents*/,
19072                    ps.readUserState(nextUserId).domainVerificationStatus,
19073                    0, PackageManager.INSTALL_REASON_UNKNOWN,
19074                    null /*harmfulAppWarning*/);
19075        }
19076        mSettings.writeKernelMappingLPr(ps);
19077    }
19078
19079    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19080            PackageRemovedInfo outInfo) {
19081        final PackageParser.Package pkg;
19082        synchronized (mPackages) {
19083            pkg = mPackages.get(ps.name);
19084        }
19085
19086        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19087                : new int[] {userId};
19088        for (int nextUserId : userIds) {
19089            if (DEBUG_REMOVE) {
19090                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19091                        + nextUserId);
19092            }
19093
19094            destroyAppDataLIF(pkg, userId,
19095                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19096            destroyAppProfilesLIF(pkg, userId);
19097            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19098            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19099            schedulePackageCleaning(ps.name, nextUserId, false);
19100            synchronized (mPackages) {
19101                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19102                    scheduleWritePackageRestrictionsLocked(nextUserId);
19103                }
19104                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19105            }
19106        }
19107
19108        if (outInfo != null) {
19109            outInfo.removedPackage = ps.name;
19110            outInfo.installerPackageName = ps.installerPackageName;
19111            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19112            outInfo.removedAppId = ps.appId;
19113            outInfo.removedUsers = userIds;
19114            outInfo.broadcastUsers = userIds;
19115        }
19116
19117        return true;
19118    }
19119
19120    private final class ClearStorageConnection implements ServiceConnection {
19121        IMediaContainerService mContainerService;
19122
19123        @Override
19124        public void onServiceConnected(ComponentName name, IBinder service) {
19125            synchronized (this) {
19126                mContainerService = IMediaContainerService.Stub
19127                        .asInterface(Binder.allowBlocking(service));
19128                notifyAll();
19129            }
19130        }
19131
19132        @Override
19133        public void onServiceDisconnected(ComponentName name) {
19134        }
19135    }
19136
19137    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19138        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19139
19140        final boolean mounted;
19141        if (Environment.isExternalStorageEmulated()) {
19142            mounted = true;
19143        } else {
19144            final String status = Environment.getExternalStorageState();
19145
19146            mounted = status.equals(Environment.MEDIA_MOUNTED)
19147                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19148        }
19149
19150        if (!mounted) {
19151            return;
19152        }
19153
19154        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19155        int[] users;
19156        if (userId == UserHandle.USER_ALL) {
19157            users = sUserManager.getUserIds();
19158        } else {
19159            users = new int[] { userId };
19160        }
19161        final ClearStorageConnection conn = new ClearStorageConnection();
19162        if (mContext.bindServiceAsUser(
19163                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19164            try {
19165                for (int curUser : users) {
19166                    long timeout = SystemClock.uptimeMillis() + 5000;
19167                    synchronized (conn) {
19168                        long now;
19169                        while (conn.mContainerService == null &&
19170                                (now = SystemClock.uptimeMillis()) < timeout) {
19171                            try {
19172                                conn.wait(timeout - now);
19173                            } catch (InterruptedException e) {
19174                            }
19175                        }
19176                    }
19177                    if (conn.mContainerService == null) {
19178                        return;
19179                    }
19180
19181                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19182                    clearDirectory(conn.mContainerService,
19183                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19184                    if (allData) {
19185                        clearDirectory(conn.mContainerService,
19186                                userEnv.buildExternalStorageAppDataDirs(packageName));
19187                        clearDirectory(conn.mContainerService,
19188                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19189                    }
19190                }
19191            } finally {
19192                mContext.unbindService(conn);
19193            }
19194        }
19195    }
19196
19197    @Override
19198    public void clearApplicationProfileData(String packageName) {
19199        enforceSystemOrRoot("Only the system can clear all profile data");
19200
19201        final PackageParser.Package pkg;
19202        synchronized (mPackages) {
19203            pkg = mPackages.get(packageName);
19204        }
19205
19206        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19207            synchronized (mInstallLock) {
19208                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19209            }
19210        }
19211    }
19212
19213    @Override
19214    public void clearApplicationUserData(final String packageName,
19215            final IPackageDataObserver observer, final int userId) {
19216        mContext.enforceCallingOrSelfPermission(
19217                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19218
19219        final int callingUid = Binder.getCallingUid();
19220        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19221                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19222
19223        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19224        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
19225        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19226            throw new SecurityException("Cannot clear data for a protected package: "
19227                    + packageName);
19228        }
19229        // Queue up an async operation since the package deletion may take a little while.
19230        mHandler.post(new Runnable() {
19231            public void run() {
19232                mHandler.removeCallbacks(this);
19233                final boolean succeeded;
19234                if (!filterApp) {
19235                    try (PackageFreezer freezer = freezePackage(packageName,
19236                            "clearApplicationUserData")) {
19237                        synchronized (mInstallLock) {
19238                            succeeded = clearApplicationUserDataLIF(packageName, userId);
19239                        }
19240                        clearExternalStorageDataSync(packageName, userId, true);
19241                        synchronized (mPackages) {
19242                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19243                                    packageName, userId);
19244                        }
19245                    }
19246                    if (succeeded) {
19247                        // invoke DeviceStorageMonitor's update method to clear any notifications
19248                        DeviceStorageMonitorInternal dsm = LocalServices
19249                                .getService(DeviceStorageMonitorInternal.class);
19250                        if (dsm != null) {
19251                            dsm.checkMemory();
19252                        }
19253                        if (checkPermission(Manifest.permission.SUSPEND_APPS, packageName, userId)
19254                                == PERMISSION_GRANTED) {
19255                            unsuspendForSuspendingPackage(packageName, userId);
19256                        }
19257                    }
19258                } else {
19259                    succeeded = false;
19260                }
19261                if (observer != null) {
19262                    try {
19263                        observer.onRemoveCompleted(packageName, succeeded);
19264                    } catch (RemoteException e) {
19265                        Log.i(TAG, "Observer no longer exists.");
19266                    }
19267                } //end if observer
19268            } //end run
19269        });
19270    }
19271
19272    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19273        if (packageName == null) {
19274            Slog.w(TAG, "Attempt to delete null packageName.");
19275            return false;
19276        }
19277
19278        // Try finding details about the requested package
19279        PackageParser.Package pkg;
19280        synchronized (mPackages) {
19281            pkg = mPackages.get(packageName);
19282            if (pkg == null) {
19283                final PackageSetting ps = mSettings.mPackages.get(packageName);
19284                if (ps != null) {
19285                    pkg = ps.pkg;
19286                }
19287            }
19288
19289            if (pkg == null) {
19290                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19291                return false;
19292            }
19293
19294            PackageSetting ps = (PackageSetting) pkg.mExtras;
19295            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19296        }
19297
19298        clearAppDataLIF(pkg, userId,
19299                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19300
19301        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19302        removeKeystoreDataIfNeeded(userId, appId);
19303
19304        UserManagerInternal umInternal = getUserManagerInternal();
19305        final int flags;
19306        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19307            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19308        } else if (umInternal.isUserRunning(userId)) {
19309            flags = StorageManager.FLAG_STORAGE_DE;
19310        } else {
19311            flags = 0;
19312        }
19313        prepareAppDataContentsLIF(pkg, userId, flags);
19314
19315        return true;
19316    }
19317
19318    /**
19319     * Reverts user permission state changes (permissions and flags) in
19320     * all packages for a given user.
19321     *
19322     * @param userId The device user for which to do a reset.
19323     */
19324    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19325        final int packageCount = mPackages.size();
19326        for (int i = 0; i < packageCount; i++) {
19327            PackageParser.Package pkg = mPackages.valueAt(i);
19328            PackageSetting ps = (PackageSetting) pkg.mExtras;
19329            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19330        }
19331    }
19332
19333    private void resetNetworkPolicies(int userId) {
19334        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19335    }
19336
19337    /**
19338     * Reverts user permission state changes (permissions and flags).
19339     *
19340     * @param ps The package for which to reset.
19341     * @param userId The device user for which to do a reset.
19342     */
19343    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19344            final PackageSetting ps, final int userId) {
19345        if (ps.pkg == null) {
19346            return;
19347        }
19348
19349        // These are flags that can change base on user actions.
19350        final int userSettableMask = FLAG_PERMISSION_USER_SET
19351                | FLAG_PERMISSION_USER_FIXED
19352                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19353                | FLAG_PERMISSION_REVIEW_REQUIRED;
19354
19355        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19356                | FLAG_PERMISSION_POLICY_FIXED;
19357
19358        boolean writeInstallPermissions = false;
19359        boolean writeRuntimePermissions = false;
19360
19361        final int permissionCount = ps.pkg.requestedPermissions.size();
19362        for (int i = 0; i < permissionCount; i++) {
19363            final String permName = ps.pkg.requestedPermissions.get(i);
19364            final BasePermission bp =
19365                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19366            if (bp == null) {
19367                continue;
19368            }
19369
19370            // If shared user we just reset the state to which only this app contributed.
19371            if (ps.sharedUser != null) {
19372                boolean used = false;
19373                final int packageCount = ps.sharedUser.packages.size();
19374                for (int j = 0; j < packageCount; j++) {
19375                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19376                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19377                            && pkg.pkg.requestedPermissions.contains(permName)) {
19378                        used = true;
19379                        break;
19380                    }
19381                }
19382                if (used) {
19383                    continue;
19384                }
19385            }
19386
19387            final PermissionsState permissionsState = ps.getPermissionsState();
19388
19389            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19390
19391            // Always clear the user settable flags.
19392            final boolean hasInstallState =
19393                    permissionsState.getInstallPermissionState(permName) != null;
19394            // If permission review is enabled and this is a legacy app, mark the
19395            // permission as requiring a review as this is the initial state.
19396            int flags = 0;
19397            if (mSettings.mPermissions.mPermissionReviewRequired
19398                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19399                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19400            }
19401            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19402                if (hasInstallState) {
19403                    writeInstallPermissions = true;
19404                } else {
19405                    writeRuntimePermissions = true;
19406                }
19407            }
19408
19409            // Below is only runtime permission handling.
19410            if (!bp.isRuntime()) {
19411                continue;
19412            }
19413
19414            // Never clobber system or policy.
19415            if ((oldFlags & policyOrSystemFlags) != 0) {
19416                continue;
19417            }
19418
19419            // If this permission was granted by default, make sure it is.
19420            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19421                if (permissionsState.grantRuntimePermission(bp, userId)
19422                        != PERMISSION_OPERATION_FAILURE) {
19423                    writeRuntimePermissions = true;
19424                }
19425            // If permission review is enabled the permissions for a legacy apps
19426            // are represented as constantly granted runtime ones, so don't revoke.
19427            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19428                // Otherwise, reset the permission.
19429                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19430                switch (revokeResult) {
19431                    case PERMISSION_OPERATION_SUCCESS:
19432                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19433                        writeRuntimePermissions = true;
19434                        final int appId = ps.appId;
19435                        mHandler.post(new Runnable() {
19436                            @Override
19437                            public void run() {
19438                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19439                            }
19440                        });
19441                    } break;
19442                }
19443            }
19444        }
19445
19446        // Synchronously write as we are taking permissions away.
19447        if (writeRuntimePermissions) {
19448            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19449        }
19450
19451        // Synchronously write as we are taking permissions away.
19452        if (writeInstallPermissions) {
19453            mSettings.writeLPr();
19454        }
19455    }
19456
19457    /**
19458     * Remove entries from the keystore daemon. Will only remove it if the
19459     * {@code appId} is valid.
19460     */
19461    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19462        if (appId < 0) {
19463            return;
19464        }
19465
19466        final KeyStore keyStore = KeyStore.getInstance();
19467        if (keyStore != null) {
19468            if (userId == UserHandle.USER_ALL) {
19469                for (final int individual : sUserManager.getUserIds()) {
19470                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19471                }
19472            } else {
19473                keyStore.clearUid(UserHandle.getUid(userId, appId));
19474            }
19475        } else {
19476            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19477        }
19478    }
19479
19480    @Override
19481    public void deleteApplicationCacheFiles(final String packageName,
19482            final IPackageDataObserver observer) {
19483        final int userId = UserHandle.getCallingUserId();
19484        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19485    }
19486
19487    @Override
19488    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19489            final IPackageDataObserver observer) {
19490        final int callingUid = Binder.getCallingUid();
19491        if (mContext.checkCallingOrSelfPermission(
19492                android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES)
19493                != PackageManager.PERMISSION_GRANTED) {
19494            // If the caller has the old delete cache permission, silently ignore.  Else throw.
19495            if (mContext.checkCallingOrSelfPermission(
19496                    android.Manifest.permission.DELETE_CACHE_FILES)
19497                    == PackageManager.PERMISSION_GRANTED) {
19498                Slog.w(TAG, "Calling uid " + callingUid + " does not have " +
19499                        android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES +
19500                        ", silently ignoring");
19501                return;
19502            }
19503            mContext.enforceCallingOrSelfPermission(
19504                    android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES, null);
19505        }
19506        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19507                /* requireFullPermission= */ true, /* checkShell= */ false,
19508                "delete application cache files");
19509        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19510                android.Manifest.permission.ACCESS_INSTANT_APPS);
19511
19512        final PackageParser.Package pkg;
19513        synchronized (mPackages) {
19514            pkg = mPackages.get(packageName);
19515        }
19516
19517        // Queue up an async operation since the package deletion may take a little while.
19518        mHandler.post(new Runnable() {
19519            public void run() {
19520                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19521                boolean doClearData = true;
19522                if (ps != null) {
19523                    final boolean targetIsInstantApp =
19524                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19525                    doClearData = !targetIsInstantApp
19526                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19527                }
19528                if (doClearData) {
19529                    synchronized (mInstallLock) {
19530                        final int flags = StorageManager.FLAG_STORAGE_DE
19531                                | StorageManager.FLAG_STORAGE_CE;
19532                        // We're only clearing cache files, so we don't care if the
19533                        // app is unfrozen and still able to run
19534                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19535                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19536                    }
19537                    clearExternalStorageDataSync(packageName, userId, false);
19538                }
19539                if (observer != null) {
19540                    try {
19541                        observer.onRemoveCompleted(packageName, true);
19542                    } catch (RemoteException e) {
19543                        Log.i(TAG, "Observer no longer exists.");
19544                    }
19545                }
19546            }
19547        });
19548    }
19549
19550    @Override
19551    public void getPackageSizeInfo(final String packageName, int userHandle,
19552            final IPackageStatsObserver observer) {
19553        throw new UnsupportedOperationException(
19554                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19555    }
19556
19557    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19558        final PackageSetting ps;
19559        synchronized (mPackages) {
19560            ps = mSettings.mPackages.get(packageName);
19561            if (ps == null) {
19562                Slog.w(TAG, "Failed to find settings for " + packageName);
19563                return false;
19564            }
19565        }
19566
19567        final String[] packageNames = { packageName };
19568        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19569        final String[] codePaths = { ps.codePathString };
19570
19571        try {
19572            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19573                    ps.appId, ceDataInodes, codePaths, stats);
19574
19575            // For now, ignore code size of packages on system partition
19576            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19577                stats.codeSize = 0;
19578            }
19579
19580            // External clients expect these to be tracked separately
19581            stats.dataSize -= stats.cacheSize;
19582
19583        } catch (InstallerException e) {
19584            Slog.w(TAG, String.valueOf(e));
19585            return false;
19586        }
19587
19588        return true;
19589    }
19590
19591    private int getUidTargetSdkVersionLockedLPr(int uid) {
19592        Object obj = mSettings.getUserIdLPr(uid);
19593        if (obj instanceof SharedUserSetting) {
19594            final SharedUserSetting sus = (SharedUserSetting) obj;
19595            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19596            final Iterator<PackageSetting> it = sus.packages.iterator();
19597            while (it.hasNext()) {
19598                final PackageSetting ps = it.next();
19599                if (ps.pkg != null) {
19600                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19601                    if (v < vers) vers = v;
19602                }
19603            }
19604            return vers;
19605        } else if (obj instanceof PackageSetting) {
19606            final PackageSetting ps = (PackageSetting) obj;
19607            if (ps.pkg != null) {
19608                return ps.pkg.applicationInfo.targetSdkVersion;
19609            }
19610        }
19611        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19612    }
19613
19614    private int getPackageTargetSdkVersionLockedLPr(String packageName) {
19615        final PackageParser.Package p = mPackages.get(packageName);
19616        if (p != null) {
19617            return p.applicationInfo.targetSdkVersion;
19618        }
19619        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19620    }
19621
19622    @Override
19623    public void addPreferredActivity(IntentFilter filter, int match,
19624            ComponentName[] set, ComponentName activity, int userId) {
19625        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19626                "Adding preferred");
19627    }
19628
19629    private void addPreferredActivityInternal(IntentFilter filter, int match,
19630            ComponentName[] set, ComponentName activity, boolean always, int userId,
19631            String opname) {
19632        // writer
19633        int callingUid = Binder.getCallingUid();
19634        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19635                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19636        if (filter.countActions() == 0) {
19637            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19638            return;
19639        }
19640        synchronized (mPackages) {
19641            if (mContext.checkCallingOrSelfPermission(
19642                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19643                    != PackageManager.PERMISSION_GRANTED) {
19644                if (getUidTargetSdkVersionLockedLPr(callingUid)
19645                        < Build.VERSION_CODES.FROYO) {
19646                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19647                            + callingUid);
19648                    return;
19649                }
19650                mContext.enforceCallingOrSelfPermission(
19651                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19652            }
19653
19654            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19655            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19656                    + userId + ":");
19657            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19658            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19659            scheduleWritePackageRestrictionsLocked(userId);
19660            postPreferredActivityChangedBroadcast(userId);
19661        }
19662    }
19663
19664    private void postPreferredActivityChangedBroadcast(int userId) {
19665        mHandler.post(() -> {
19666            final IActivityManager am = ActivityManager.getService();
19667            if (am == null) {
19668                return;
19669            }
19670
19671            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19672            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19673            try {
19674                am.broadcastIntent(null, intent, null, null,
19675                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19676                        null, false, false, userId);
19677            } catch (RemoteException e) {
19678            }
19679        });
19680    }
19681
19682    @Override
19683    public void replacePreferredActivity(IntentFilter filter, int match,
19684            ComponentName[] set, ComponentName activity, int userId) {
19685        if (filter.countActions() != 1) {
19686            throw new IllegalArgumentException(
19687                    "replacePreferredActivity expects filter to have only 1 action.");
19688        }
19689        if (filter.countDataAuthorities() != 0
19690                || filter.countDataPaths() != 0
19691                || filter.countDataSchemes() > 1
19692                || filter.countDataTypes() != 0) {
19693            throw new IllegalArgumentException(
19694                    "replacePreferredActivity expects filter to have no data authorities, " +
19695                    "paths, or types; and at most one scheme.");
19696        }
19697
19698        final int callingUid = Binder.getCallingUid();
19699        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19700                true /* requireFullPermission */, false /* checkShell */,
19701                "replace preferred activity");
19702        synchronized (mPackages) {
19703            if (mContext.checkCallingOrSelfPermission(
19704                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19705                    != PackageManager.PERMISSION_GRANTED) {
19706                if (getUidTargetSdkVersionLockedLPr(callingUid)
19707                        < Build.VERSION_CODES.FROYO) {
19708                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19709                            + Binder.getCallingUid());
19710                    return;
19711                }
19712                mContext.enforceCallingOrSelfPermission(
19713                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19714            }
19715
19716            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19717            if (pir != null) {
19718                // Get all of the existing entries that exactly match this filter.
19719                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19720                if (existing != null && existing.size() == 1) {
19721                    PreferredActivity cur = existing.get(0);
19722                    if (DEBUG_PREFERRED) {
19723                        Slog.i(TAG, "Checking replace of preferred:");
19724                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19725                        if (!cur.mPref.mAlways) {
19726                            Slog.i(TAG, "  -- CUR; not mAlways!");
19727                        } else {
19728                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19729                            Slog.i(TAG, "  -- CUR: mSet="
19730                                    + Arrays.toString(cur.mPref.mSetComponents));
19731                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19732                            Slog.i(TAG, "  -- NEW: mMatch="
19733                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19734                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19735                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19736                        }
19737                    }
19738                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19739                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19740                            && cur.mPref.sameSet(set)) {
19741                        // Setting the preferred activity to what it happens to be already
19742                        if (DEBUG_PREFERRED) {
19743                            Slog.i(TAG, "Replacing with same preferred activity "
19744                                    + cur.mPref.mShortComponent + " for user "
19745                                    + userId + ":");
19746                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19747                        }
19748                        return;
19749                    }
19750                }
19751
19752                if (existing != null) {
19753                    if (DEBUG_PREFERRED) {
19754                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19755                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19756                    }
19757                    for (int i = 0; i < existing.size(); i++) {
19758                        PreferredActivity pa = existing.get(i);
19759                        if (DEBUG_PREFERRED) {
19760                            Slog.i(TAG, "Removing existing preferred activity "
19761                                    + pa.mPref.mComponent + ":");
19762                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19763                        }
19764                        pir.removeFilter(pa);
19765                    }
19766                }
19767            }
19768            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19769                    "Replacing preferred");
19770        }
19771    }
19772
19773    @Override
19774    public void clearPackagePreferredActivities(String packageName) {
19775        final int callingUid = Binder.getCallingUid();
19776        if (getInstantAppPackageName(callingUid) != null) {
19777            return;
19778        }
19779        // writer
19780        synchronized (mPackages) {
19781            PackageParser.Package pkg = mPackages.get(packageName);
19782            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19783                if (mContext.checkCallingOrSelfPermission(
19784                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19785                        != PackageManager.PERMISSION_GRANTED) {
19786                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19787                            < Build.VERSION_CODES.FROYO) {
19788                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19789                                + callingUid);
19790                        return;
19791                    }
19792                    mContext.enforceCallingOrSelfPermission(
19793                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19794                }
19795            }
19796            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19797            if (ps != null
19798                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19799                return;
19800            }
19801            int user = UserHandle.getCallingUserId();
19802            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19803                scheduleWritePackageRestrictionsLocked(user);
19804            }
19805        }
19806    }
19807
19808    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19809    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19810        ArrayList<PreferredActivity> removed = null;
19811        boolean changed = false;
19812        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19813            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19814            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19815            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19816                continue;
19817            }
19818            Iterator<PreferredActivity> it = pir.filterIterator();
19819            while (it.hasNext()) {
19820                PreferredActivity pa = it.next();
19821                // Mark entry for removal only if it matches the package name
19822                // and the entry is of type "always".
19823                if (packageName == null ||
19824                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19825                                && pa.mPref.mAlways)) {
19826                    if (removed == null) {
19827                        removed = new ArrayList<PreferredActivity>();
19828                    }
19829                    removed.add(pa);
19830                }
19831            }
19832            if (removed != null) {
19833                for (int j=0; j<removed.size(); j++) {
19834                    PreferredActivity pa = removed.get(j);
19835                    pir.removeFilter(pa);
19836                }
19837                changed = true;
19838            }
19839        }
19840        if (changed) {
19841            postPreferredActivityChangedBroadcast(userId);
19842        }
19843        return changed;
19844    }
19845
19846    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19847    private void clearIntentFilterVerificationsLPw(int userId) {
19848        final int packageCount = mPackages.size();
19849        for (int i = 0; i < packageCount; i++) {
19850            PackageParser.Package pkg = mPackages.valueAt(i);
19851            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19852        }
19853    }
19854
19855    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19856    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19857        if (userId == UserHandle.USER_ALL) {
19858            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19859                    sUserManager.getUserIds())) {
19860                for (int oneUserId : sUserManager.getUserIds()) {
19861                    scheduleWritePackageRestrictionsLocked(oneUserId);
19862                }
19863            }
19864        } else {
19865            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19866                scheduleWritePackageRestrictionsLocked(userId);
19867            }
19868        }
19869    }
19870
19871    /** Clears state for all users, and touches intent filter verification policy */
19872    void clearDefaultBrowserIfNeeded(String packageName) {
19873        for (int oneUserId : sUserManager.getUserIds()) {
19874            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19875        }
19876    }
19877
19878    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19879        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19880        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19881            if (packageName.equals(defaultBrowserPackageName)) {
19882                setDefaultBrowserPackageName(null, userId);
19883            }
19884        }
19885    }
19886
19887    @Override
19888    public void resetApplicationPreferences(int userId) {
19889        mContext.enforceCallingOrSelfPermission(
19890                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19891        final long identity = Binder.clearCallingIdentity();
19892        // writer
19893        try {
19894            synchronized (mPackages) {
19895                clearPackagePreferredActivitiesLPw(null, userId);
19896                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19897                // TODO: We have to reset the default SMS and Phone. This requires
19898                // significant refactoring to keep all default apps in the package
19899                // manager (cleaner but more work) or have the services provide
19900                // callbacks to the package manager to request a default app reset.
19901                applyFactoryDefaultBrowserLPw(userId);
19902                clearIntentFilterVerificationsLPw(userId);
19903                primeDomainVerificationsLPw(userId);
19904                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19905                scheduleWritePackageRestrictionsLocked(userId);
19906            }
19907            resetNetworkPolicies(userId);
19908        } finally {
19909            Binder.restoreCallingIdentity(identity);
19910        }
19911    }
19912
19913    @Override
19914    public int getPreferredActivities(List<IntentFilter> outFilters,
19915            List<ComponentName> outActivities, String packageName) {
19916        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19917            return 0;
19918        }
19919        int num = 0;
19920        final int userId = UserHandle.getCallingUserId();
19921        // reader
19922        synchronized (mPackages) {
19923            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19924            if (pir != null) {
19925                final Iterator<PreferredActivity> it = pir.filterIterator();
19926                while (it.hasNext()) {
19927                    final PreferredActivity pa = it.next();
19928                    if (packageName == null
19929                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19930                                    && pa.mPref.mAlways)) {
19931                        if (outFilters != null) {
19932                            outFilters.add(new IntentFilter(pa));
19933                        }
19934                        if (outActivities != null) {
19935                            outActivities.add(pa.mPref.mComponent);
19936                        }
19937                    }
19938                }
19939            }
19940        }
19941
19942        return num;
19943    }
19944
19945    @Override
19946    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19947            int userId) {
19948        int callingUid = Binder.getCallingUid();
19949        if (callingUid != Process.SYSTEM_UID) {
19950            throw new SecurityException(
19951                    "addPersistentPreferredActivity can only be run by the system");
19952        }
19953        if (filter.countActions() == 0) {
19954            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19955            return;
19956        }
19957        synchronized (mPackages) {
19958            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19959                    ":");
19960            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19961            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19962                    new PersistentPreferredActivity(filter, activity));
19963            scheduleWritePackageRestrictionsLocked(userId);
19964            postPreferredActivityChangedBroadcast(userId);
19965        }
19966    }
19967
19968    @Override
19969    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19970        int callingUid = Binder.getCallingUid();
19971        if (callingUid != Process.SYSTEM_UID) {
19972            throw new SecurityException(
19973                    "clearPackagePersistentPreferredActivities can only be run by the system");
19974        }
19975        ArrayList<PersistentPreferredActivity> removed = null;
19976        boolean changed = false;
19977        synchronized (mPackages) {
19978            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19979                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19980                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19981                        .valueAt(i);
19982                if (userId != thisUserId) {
19983                    continue;
19984                }
19985                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19986                while (it.hasNext()) {
19987                    PersistentPreferredActivity ppa = it.next();
19988                    // Mark entry for removal only if it matches the package name.
19989                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19990                        if (removed == null) {
19991                            removed = new ArrayList<PersistentPreferredActivity>();
19992                        }
19993                        removed.add(ppa);
19994                    }
19995                }
19996                if (removed != null) {
19997                    for (int j=0; j<removed.size(); j++) {
19998                        PersistentPreferredActivity ppa = removed.get(j);
19999                        ppir.removeFilter(ppa);
20000                    }
20001                    changed = true;
20002                }
20003            }
20004
20005            if (changed) {
20006                scheduleWritePackageRestrictionsLocked(userId);
20007                postPreferredActivityChangedBroadcast(userId);
20008            }
20009        }
20010    }
20011
20012    /**
20013     * Common machinery for picking apart a restored XML blob and passing
20014     * it to a caller-supplied functor to be applied to the running system.
20015     */
20016    private void restoreFromXml(XmlPullParser parser, int userId,
20017            String expectedStartTag, BlobXmlRestorer functor)
20018            throws IOException, XmlPullParserException {
20019        int type;
20020        while ((type = parser.next()) != XmlPullParser.START_TAG
20021                && type != XmlPullParser.END_DOCUMENT) {
20022        }
20023        if (type != XmlPullParser.START_TAG) {
20024            // oops didn't find a start tag?!
20025            if (DEBUG_BACKUP) {
20026                Slog.e(TAG, "Didn't find start tag during restore");
20027            }
20028            return;
20029        }
20030Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20031        // this is supposed to be TAG_PREFERRED_BACKUP
20032        if (!expectedStartTag.equals(parser.getName())) {
20033            if (DEBUG_BACKUP) {
20034                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20035            }
20036            return;
20037        }
20038
20039        // skip interfering stuff, then we're aligned with the backing implementation
20040        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20041Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20042        functor.apply(parser, userId);
20043    }
20044
20045    private interface BlobXmlRestorer {
20046        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20047    }
20048
20049    /**
20050     * Non-Binder method, support for the backup/restore mechanism: write the
20051     * full set of preferred activities in its canonical XML format.  Returns the
20052     * XML output as a byte array, or null if there is none.
20053     */
20054    @Override
20055    public byte[] getPreferredActivityBackup(int userId) {
20056        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20057            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20058        }
20059
20060        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20061        try {
20062            final XmlSerializer serializer = new FastXmlSerializer();
20063            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20064            serializer.startDocument(null, true);
20065            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20066
20067            synchronized (mPackages) {
20068                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20069            }
20070
20071            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20072            serializer.endDocument();
20073            serializer.flush();
20074        } catch (Exception e) {
20075            if (DEBUG_BACKUP) {
20076                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20077            }
20078            return null;
20079        }
20080
20081        return dataStream.toByteArray();
20082    }
20083
20084    @Override
20085    public void restorePreferredActivities(byte[] backup, int userId) {
20086        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20087            throw new SecurityException("Only the system may call restorePreferredActivities()");
20088        }
20089
20090        try {
20091            final XmlPullParser parser = Xml.newPullParser();
20092            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20093            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20094                    new BlobXmlRestorer() {
20095                        @Override
20096                        public void apply(XmlPullParser parser, int userId)
20097                                throws XmlPullParserException, IOException {
20098                            synchronized (mPackages) {
20099                                mSettings.readPreferredActivitiesLPw(parser, userId);
20100                            }
20101                        }
20102                    } );
20103        } catch (Exception e) {
20104            if (DEBUG_BACKUP) {
20105                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20106            }
20107        }
20108    }
20109
20110    /**
20111     * Non-Binder method, support for the backup/restore mechanism: write the
20112     * default browser (etc) settings in its canonical XML format.  Returns the default
20113     * browser XML representation as a byte array, or null if there is none.
20114     */
20115    @Override
20116    public byte[] getDefaultAppsBackup(int userId) {
20117        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20118            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20119        }
20120
20121        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20122        try {
20123            final XmlSerializer serializer = new FastXmlSerializer();
20124            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20125            serializer.startDocument(null, true);
20126            serializer.startTag(null, TAG_DEFAULT_APPS);
20127
20128            synchronized (mPackages) {
20129                mSettings.writeDefaultAppsLPr(serializer, userId);
20130            }
20131
20132            serializer.endTag(null, TAG_DEFAULT_APPS);
20133            serializer.endDocument();
20134            serializer.flush();
20135        } catch (Exception e) {
20136            if (DEBUG_BACKUP) {
20137                Slog.e(TAG, "Unable to write default apps for backup", e);
20138            }
20139            return null;
20140        }
20141
20142        return dataStream.toByteArray();
20143    }
20144
20145    @Override
20146    public void restoreDefaultApps(byte[] backup, int userId) {
20147        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20148            throw new SecurityException("Only the system may call restoreDefaultApps()");
20149        }
20150
20151        try {
20152            final XmlPullParser parser = Xml.newPullParser();
20153            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20154            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20155                    new BlobXmlRestorer() {
20156                        @Override
20157                        public void apply(XmlPullParser parser, int userId)
20158                                throws XmlPullParserException, IOException {
20159                            synchronized (mPackages) {
20160                                mSettings.readDefaultAppsLPw(parser, userId);
20161                            }
20162                        }
20163                    } );
20164        } catch (Exception e) {
20165            if (DEBUG_BACKUP) {
20166                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20167            }
20168        }
20169    }
20170
20171    @Override
20172    public byte[] getIntentFilterVerificationBackup(int userId) {
20173        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20174            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20175        }
20176
20177        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20178        try {
20179            final XmlSerializer serializer = new FastXmlSerializer();
20180            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20181            serializer.startDocument(null, true);
20182            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20183
20184            synchronized (mPackages) {
20185                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20186            }
20187
20188            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20189            serializer.endDocument();
20190            serializer.flush();
20191        } catch (Exception e) {
20192            if (DEBUG_BACKUP) {
20193                Slog.e(TAG, "Unable to write default apps for backup", e);
20194            }
20195            return null;
20196        }
20197
20198        return dataStream.toByteArray();
20199    }
20200
20201    @Override
20202    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20203        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20204            throw new SecurityException("Only the system may call restorePreferredActivities()");
20205        }
20206
20207        try {
20208            final XmlPullParser parser = Xml.newPullParser();
20209            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20210            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20211                    new BlobXmlRestorer() {
20212                        @Override
20213                        public void apply(XmlPullParser parser, int userId)
20214                                throws XmlPullParserException, IOException {
20215                            synchronized (mPackages) {
20216                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20217                                mSettings.writeLPr();
20218                            }
20219                        }
20220                    } );
20221        } catch (Exception e) {
20222            if (DEBUG_BACKUP) {
20223                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20224            }
20225        }
20226    }
20227
20228    @Override
20229    public byte[] getPermissionGrantBackup(int userId) {
20230        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20231            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20232        }
20233
20234        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20235        try {
20236            final XmlSerializer serializer = new FastXmlSerializer();
20237            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20238            serializer.startDocument(null, true);
20239            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20240
20241            synchronized (mPackages) {
20242                serializeRuntimePermissionGrantsLPr(serializer, userId);
20243            }
20244
20245            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20246            serializer.endDocument();
20247            serializer.flush();
20248        } catch (Exception e) {
20249            if (DEBUG_BACKUP) {
20250                Slog.e(TAG, "Unable to write default apps for backup", e);
20251            }
20252            return null;
20253        }
20254
20255        return dataStream.toByteArray();
20256    }
20257
20258    @Override
20259    public void restorePermissionGrants(byte[] backup, int userId) {
20260        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20261            throw new SecurityException("Only the system may call restorePermissionGrants()");
20262        }
20263
20264        try {
20265            final XmlPullParser parser = Xml.newPullParser();
20266            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20267            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20268                    new BlobXmlRestorer() {
20269                        @Override
20270                        public void apply(XmlPullParser parser, int userId)
20271                                throws XmlPullParserException, IOException {
20272                            synchronized (mPackages) {
20273                                processRestoredPermissionGrantsLPr(parser, userId);
20274                            }
20275                        }
20276                    } );
20277        } catch (Exception e) {
20278            if (DEBUG_BACKUP) {
20279                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20280            }
20281        }
20282    }
20283
20284    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20285            throws IOException {
20286        serializer.startTag(null, TAG_ALL_GRANTS);
20287
20288        final int N = mSettings.mPackages.size();
20289        for (int i = 0; i < N; i++) {
20290            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20291            boolean pkgGrantsKnown = false;
20292
20293            PermissionsState packagePerms = ps.getPermissionsState();
20294
20295            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20296                final int grantFlags = state.getFlags();
20297                // only look at grants that are not system/policy fixed
20298                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20299                    final boolean isGranted = state.isGranted();
20300                    // And only back up the user-twiddled state bits
20301                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20302                        final String packageName = mSettings.mPackages.keyAt(i);
20303                        if (!pkgGrantsKnown) {
20304                            serializer.startTag(null, TAG_GRANT);
20305                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20306                            pkgGrantsKnown = true;
20307                        }
20308
20309                        final boolean userSet =
20310                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20311                        final boolean userFixed =
20312                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20313                        final boolean revoke =
20314                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20315
20316                        serializer.startTag(null, TAG_PERMISSION);
20317                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20318                        if (isGranted) {
20319                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20320                        }
20321                        if (userSet) {
20322                            serializer.attribute(null, ATTR_USER_SET, "true");
20323                        }
20324                        if (userFixed) {
20325                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20326                        }
20327                        if (revoke) {
20328                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20329                        }
20330                        serializer.endTag(null, TAG_PERMISSION);
20331                    }
20332                }
20333            }
20334
20335            if (pkgGrantsKnown) {
20336                serializer.endTag(null, TAG_GRANT);
20337            }
20338        }
20339
20340        serializer.endTag(null, TAG_ALL_GRANTS);
20341    }
20342
20343    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20344            throws XmlPullParserException, IOException {
20345        String pkgName = null;
20346        int outerDepth = parser.getDepth();
20347        int type;
20348        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20349                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20350            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20351                continue;
20352            }
20353
20354            final String tagName = parser.getName();
20355            if (tagName.equals(TAG_GRANT)) {
20356                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20357                if (DEBUG_BACKUP) {
20358                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20359                }
20360            } else if (tagName.equals(TAG_PERMISSION)) {
20361
20362                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20363                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20364
20365                int newFlagSet = 0;
20366                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20367                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20368                }
20369                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20370                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20371                }
20372                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20373                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20374                }
20375                if (DEBUG_BACKUP) {
20376                    Slog.v(TAG, "  + Restoring grant:"
20377                            + " pkg=" + pkgName
20378                            + " perm=" + permName
20379                            + " granted=" + isGranted
20380                            + " bits=0x" + Integer.toHexString(newFlagSet));
20381                }
20382                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20383                if (ps != null) {
20384                    // Already installed so we apply the grant immediately
20385                    if (DEBUG_BACKUP) {
20386                        Slog.v(TAG, "        + already installed; applying");
20387                    }
20388                    PermissionsState perms = ps.getPermissionsState();
20389                    BasePermission bp =
20390                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
20391                    if (bp != null) {
20392                        if (isGranted) {
20393                            perms.grantRuntimePermission(bp, userId);
20394                        }
20395                        if (newFlagSet != 0) {
20396                            perms.updatePermissionFlags(
20397                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20398                        }
20399                    }
20400                } else {
20401                    // Need to wait for post-restore install to apply the grant
20402                    if (DEBUG_BACKUP) {
20403                        Slog.v(TAG, "        - not yet installed; saving for later");
20404                    }
20405                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20406                            isGranted, newFlagSet, userId);
20407                }
20408            } else {
20409                PackageManagerService.reportSettingsProblem(Log.WARN,
20410                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20411                XmlUtils.skipCurrentTag(parser);
20412            }
20413        }
20414
20415        scheduleWriteSettingsLocked();
20416        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20417    }
20418
20419    @Override
20420    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20421            int sourceUserId, int targetUserId, int flags) {
20422        mContext.enforceCallingOrSelfPermission(
20423                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20424        int callingUid = Binder.getCallingUid();
20425        enforceOwnerRights(ownerPackage, callingUid);
20426        PackageManagerServiceUtils.enforceShellRestriction(
20427                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20428        if (intentFilter.countActions() == 0) {
20429            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20430            return;
20431        }
20432        synchronized (mPackages) {
20433            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20434                    ownerPackage, targetUserId, flags);
20435            CrossProfileIntentResolver resolver =
20436                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20437            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20438            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20439            if (existing != null) {
20440                int size = existing.size();
20441                for (int i = 0; i < size; i++) {
20442                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20443                        return;
20444                    }
20445                }
20446            }
20447            resolver.addFilter(newFilter);
20448            scheduleWritePackageRestrictionsLocked(sourceUserId);
20449        }
20450    }
20451
20452    @Override
20453    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20454        mContext.enforceCallingOrSelfPermission(
20455                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20456        final int callingUid = Binder.getCallingUid();
20457        enforceOwnerRights(ownerPackage, callingUid);
20458        PackageManagerServiceUtils.enforceShellRestriction(
20459                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20460        synchronized (mPackages) {
20461            CrossProfileIntentResolver resolver =
20462                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20463            ArraySet<CrossProfileIntentFilter> set =
20464                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20465            for (CrossProfileIntentFilter filter : set) {
20466                if (filter.getOwnerPackage().equals(ownerPackage)) {
20467                    resolver.removeFilter(filter);
20468                }
20469            }
20470            scheduleWritePackageRestrictionsLocked(sourceUserId);
20471        }
20472    }
20473
20474    // Enforcing that callingUid is owning pkg on userId
20475    private void enforceOwnerRights(String pkg, int callingUid) {
20476        // The system owns everything.
20477        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20478            return;
20479        }
20480        final int callingUserId = UserHandle.getUserId(callingUid);
20481        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20482        if (pi == null) {
20483            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20484                    + callingUserId);
20485        }
20486        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20487            throw new SecurityException("Calling uid " + callingUid
20488                    + " does not own package " + pkg);
20489        }
20490    }
20491
20492    @Override
20493    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20494        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20495            return null;
20496        }
20497        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20498    }
20499
20500    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20501        UserManagerService ums = UserManagerService.getInstance();
20502        if (ums != null) {
20503            final UserInfo parent = ums.getProfileParent(userId);
20504            final int launcherUid = (parent != null) ? parent.id : userId;
20505            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20506            if (launcherComponent != null) {
20507                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20508                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20509                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20510                        .setPackage(launcherComponent.getPackageName());
20511                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20512            }
20513        }
20514    }
20515
20516    /**
20517     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20518     * then reports the most likely home activity or null if there are more than one.
20519     */
20520    private ComponentName getDefaultHomeActivity(int userId) {
20521        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20522        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20523        if (cn != null) {
20524            return cn;
20525        }
20526
20527        // Find the launcher with the highest priority and return that component if there are no
20528        // other home activity with the same priority.
20529        int lastPriority = Integer.MIN_VALUE;
20530        ComponentName lastComponent = null;
20531        final int size = allHomeCandidates.size();
20532        for (int i = 0; i < size; i++) {
20533            final ResolveInfo ri = allHomeCandidates.get(i);
20534            if (ri.priority > lastPriority) {
20535                lastComponent = ri.activityInfo.getComponentName();
20536                lastPriority = ri.priority;
20537            } else if (ri.priority == lastPriority) {
20538                // Two components found with same priority.
20539                lastComponent = null;
20540            }
20541        }
20542        return lastComponent;
20543    }
20544
20545    private Intent getHomeIntent() {
20546        Intent intent = new Intent(Intent.ACTION_MAIN);
20547        intent.addCategory(Intent.CATEGORY_HOME);
20548        intent.addCategory(Intent.CATEGORY_DEFAULT);
20549        return intent;
20550    }
20551
20552    private IntentFilter getHomeFilter() {
20553        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20554        filter.addCategory(Intent.CATEGORY_HOME);
20555        filter.addCategory(Intent.CATEGORY_DEFAULT);
20556        return filter;
20557    }
20558
20559    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20560            int userId) {
20561        Intent intent  = getHomeIntent();
20562        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20563                PackageManager.GET_META_DATA, userId);
20564        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20565                true, false, false, userId);
20566
20567        allHomeCandidates.clear();
20568        if (list != null) {
20569            for (ResolveInfo ri : list) {
20570                allHomeCandidates.add(ri);
20571            }
20572        }
20573        return (preferred == null || preferred.activityInfo == null)
20574                ? null
20575                : new ComponentName(preferred.activityInfo.packageName,
20576                        preferred.activityInfo.name);
20577    }
20578
20579    @Override
20580    public void setHomeActivity(ComponentName comp, int userId) {
20581        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20582            return;
20583        }
20584        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20585        getHomeActivitiesAsUser(homeActivities, userId);
20586
20587        boolean found = false;
20588
20589        final int size = homeActivities.size();
20590        final ComponentName[] set = new ComponentName[size];
20591        for (int i = 0; i < size; i++) {
20592            final ResolveInfo candidate = homeActivities.get(i);
20593            final ActivityInfo info = candidate.activityInfo;
20594            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20595            set[i] = activityName;
20596            if (!found && activityName.equals(comp)) {
20597                found = true;
20598            }
20599        }
20600        if (!found) {
20601            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20602                    + userId);
20603        }
20604        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20605                set, comp, userId);
20606    }
20607
20608    private @Nullable String getSetupWizardPackageName() {
20609        final Intent intent = new Intent(Intent.ACTION_MAIN);
20610        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20611
20612        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20613                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20614                        | MATCH_DISABLED_COMPONENTS,
20615                UserHandle.myUserId());
20616        if (matches.size() == 1) {
20617            return matches.get(0).getComponentInfo().packageName;
20618        } else {
20619            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20620                    + ": matches=" + matches);
20621            return null;
20622        }
20623    }
20624
20625    private @Nullable String getStorageManagerPackageName() {
20626        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20627
20628        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20629                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20630                        | MATCH_DISABLED_COMPONENTS,
20631                UserHandle.myUserId());
20632        if (matches.size() == 1) {
20633            return matches.get(0).getComponentInfo().packageName;
20634        } else {
20635            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20636                    + matches.size() + ": matches=" + matches);
20637            return null;
20638        }
20639    }
20640
20641    @Override
20642    public String getSystemTextClassifierPackageName() {
20643        return mContext.getString(R.string.config_defaultTextClassifierPackage);
20644    }
20645
20646    @Override
20647    public void setApplicationEnabledSetting(String appPackageName,
20648            int newState, int flags, int userId, String callingPackage) {
20649        if (!sUserManager.exists(userId)) return;
20650        if (callingPackage == null) {
20651            callingPackage = Integer.toString(Binder.getCallingUid());
20652        }
20653        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20654    }
20655
20656    @Override
20657    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20658        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20659        synchronized (mPackages) {
20660            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20661            if (pkgSetting != null) {
20662                pkgSetting.setUpdateAvailable(updateAvailable);
20663            }
20664        }
20665    }
20666
20667    @Override
20668    public void setComponentEnabledSetting(ComponentName componentName,
20669            int newState, int flags, int userId) {
20670        if (!sUserManager.exists(userId)) return;
20671        setEnabledSetting(componentName.getPackageName(),
20672                componentName.getClassName(), newState, flags, userId, null);
20673    }
20674
20675    private void setEnabledSetting(final String packageName, String className, int newState,
20676            final int flags, int userId, String callingPackage) {
20677        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20678              || newState == COMPONENT_ENABLED_STATE_ENABLED
20679              || newState == COMPONENT_ENABLED_STATE_DISABLED
20680              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20681              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20682            throw new IllegalArgumentException("Invalid new component state: "
20683                    + newState);
20684        }
20685        PackageSetting pkgSetting;
20686        final int callingUid = Binder.getCallingUid();
20687        final int permission;
20688        if (callingUid == Process.SYSTEM_UID) {
20689            permission = PackageManager.PERMISSION_GRANTED;
20690        } else {
20691            permission = mContext.checkCallingOrSelfPermission(
20692                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20693        }
20694        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20695                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20696        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20697        boolean sendNow = false;
20698        boolean isApp = (className == null);
20699        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20700        String componentName = isApp ? packageName : className;
20701        int packageUid = -1;
20702        ArrayList<String> components;
20703
20704        // reader
20705        synchronized (mPackages) {
20706            pkgSetting = mSettings.mPackages.get(packageName);
20707            if (pkgSetting == null) {
20708                if (!isCallerInstantApp) {
20709                    if (className == null) {
20710                        throw new IllegalArgumentException("Unknown package: " + packageName);
20711                    }
20712                    throw new IllegalArgumentException(
20713                            "Unknown component: " + packageName + "/" + className);
20714                } else {
20715                    // throw SecurityException to prevent leaking package information
20716                    throw new SecurityException(
20717                            "Attempt to change component state; "
20718                            + "pid=" + Binder.getCallingPid()
20719                            + ", uid=" + callingUid
20720                            + (className == null
20721                                    ? ", package=" + packageName
20722                                    : ", component=" + packageName + "/" + className));
20723                }
20724            }
20725        }
20726
20727        // Limit who can change which apps
20728        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20729            // Don't allow apps that don't have permission to modify other apps
20730            if (!allowedByPermission
20731                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20732                throw new SecurityException(
20733                        "Attempt to change component state; "
20734                        + "pid=" + Binder.getCallingPid()
20735                        + ", uid=" + callingUid
20736                        + (className == null
20737                                ? ", package=" + packageName
20738                                : ", component=" + packageName + "/" + className));
20739            }
20740            // Don't allow changing protected packages.
20741            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20742                throw new SecurityException("Cannot disable a protected package: " + packageName);
20743            }
20744        }
20745
20746        synchronized (mPackages) {
20747            if (callingUid == Process.SHELL_UID
20748                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20749                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20750                // unless it is a test package.
20751                int oldState = pkgSetting.getEnabled(userId);
20752                if (className == null
20753                        &&
20754                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20755                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20756                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20757                        &&
20758                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20759                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20760                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20761                    // ok
20762                } else {
20763                    throw new SecurityException(
20764                            "Shell cannot change component state for " + packageName + "/"
20765                                    + className + " to " + newState);
20766                }
20767            }
20768        }
20769        if (className == null) {
20770            // We're dealing with an application/package level state change
20771            synchronized (mPackages) {
20772                if (pkgSetting.getEnabled(userId) == newState) {
20773                    // Nothing to do
20774                    return;
20775                }
20776            }
20777            // If we're enabling a system stub, there's a little more work to do.
20778            // Prior to enabling the package, we need to decompress the APK(s) to the
20779            // data partition and then replace the version on the system partition.
20780            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20781            final boolean isSystemStub = deletedPkg.isStub
20782                    && deletedPkg.isSystem();
20783            if (isSystemStub
20784                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20785                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20786                final File codePath = decompressPackage(deletedPkg);
20787                if (codePath == null) {
20788                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20789                    return;
20790                }
20791                // TODO remove direct parsing of the package object during internal cleanup
20792                // of scan package
20793                // We need to call parse directly here for no other reason than we need
20794                // the new package in order to disable the old one [we use the information
20795                // for some internal optimization to optionally create a new package setting
20796                // object on replace]. However, we can't get the package from the scan
20797                // because the scan modifies live structures and we need to remove the
20798                // old [system] package from the system before a scan can be attempted.
20799                // Once scan is indempotent we can remove this parse and use the package
20800                // object we scanned, prior to adding it to package settings.
20801                final PackageParser pp = new PackageParser();
20802                pp.setSeparateProcesses(mSeparateProcesses);
20803                pp.setDisplayMetrics(mMetrics);
20804                pp.setCallback(mPackageParserCallback);
20805                final PackageParser.Package tmpPkg;
20806                try {
20807                    final @ParseFlags int parseFlags = mDefParseFlags
20808                            | PackageParser.PARSE_MUST_BE_APK
20809                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20810                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20811                } catch (PackageParserException e) {
20812                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20813                    return;
20814                }
20815                synchronized (mInstallLock) {
20816                    // Disable the stub and remove any package entries
20817                    removePackageLI(deletedPkg, true);
20818                    synchronized (mPackages) {
20819                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20820                    }
20821                    final PackageParser.Package pkg;
20822                    try (PackageFreezer freezer =
20823                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20824                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20825                                | PackageParser.PARSE_ENFORCE_CODE;
20826                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20827                                0 /*currentTime*/, null /*user*/);
20828                        prepareAppDataAfterInstallLIF(pkg);
20829                        synchronized (mPackages) {
20830                            try {
20831                                updateSharedLibrariesLPr(pkg, null);
20832                            } catch (PackageManagerException e) {
20833                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20834                            }
20835                            mPermissionManager.updatePermissions(
20836                                    pkg.packageName, pkg, true, mPackages.values(),
20837                                    mPermissionCallback);
20838                            mSettings.writeLPr();
20839                        }
20840                    } catch (PackageManagerException e) {
20841                        // Whoops! Something went wrong; try to roll back to the stub
20842                        Slog.w(TAG, "Failed to install compressed system package:"
20843                                + pkgSetting.name, e);
20844                        // Remove the failed install
20845                        removeCodePathLI(codePath);
20846
20847                        // Install the system package
20848                        try (PackageFreezer freezer =
20849                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20850                            synchronized (mPackages) {
20851                                // NOTE: The system package always needs to be enabled; even
20852                                // if it's for a compressed stub. If we don't, installing the
20853                                // system package fails during scan [scanning checks the disabled
20854                                // packages]. We will reverse this later, after we've "installed"
20855                                // the stub.
20856                                // This leaves us in a fragile state; the stub should never be
20857                                // enabled, so, cross your fingers and hope nothing goes wrong
20858                                // until we can disable the package later.
20859                                enableSystemPackageLPw(deletedPkg);
20860                            }
20861                            installPackageFromSystemLIF(deletedPkg.codePath,
20862                                    false /*isPrivileged*/, null /*allUserHandles*/,
20863                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20864                                    true /*writeSettings*/);
20865                        } catch (PackageManagerException pme) {
20866                            Slog.w(TAG, "Failed to restore system package:"
20867                                    + deletedPkg.packageName, pme);
20868                        } finally {
20869                            synchronized (mPackages) {
20870                                mSettings.disableSystemPackageLPw(
20871                                        deletedPkg.packageName, true /*replaced*/);
20872                                mSettings.writeLPr();
20873                            }
20874                        }
20875                        return;
20876                    }
20877                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20878                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20879                    mDexManager.notifyPackageUpdated(pkg.packageName,
20880                            pkg.baseCodePath, pkg.splitCodePaths);
20881                }
20882            }
20883            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20884                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20885                // Don't care about who enables an app.
20886                callingPackage = null;
20887            }
20888            synchronized (mPackages) {
20889                pkgSetting.setEnabled(newState, userId, callingPackage);
20890            }
20891        } else {
20892            synchronized (mPackages) {
20893                // We're dealing with a component level state change
20894                // First, verify that this is a valid class name.
20895                PackageParser.Package pkg = pkgSetting.pkg;
20896                if (pkg == null || !pkg.hasComponentClassName(className)) {
20897                    if (pkg != null &&
20898                            pkg.applicationInfo.targetSdkVersion >=
20899                                    Build.VERSION_CODES.JELLY_BEAN) {
20900                        throw new IllegalArgumentException("Component class " + className
20901                                + " does not exist in " + packageName);
20902                    } else {
20903                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20904                                + className + " does not exist in " + packageName);
20905                    }
20906                }
20907                switch (newState) {
20908                    case COMPONENT_ENABLED_STATE_ENABLED:
20909                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20910                            return;
20911                        }
20912                        break;
20913                    case COMPONENT_ENABLED_STATE_DISABLED:
20914                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20915                            return;
20916                        }
20917                        break;
20918                    case COMPONENT_ENABLED_STATE_DEFAULT:
20919                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20920                            return;
20921                        }
20922                        break;
20923                    default:
20924                        Slog.e(TAG, "Invalid new component state: " + newState);
20925                        return;
20926                }
20927            }
20928        }
20929        synchronized (mPackages) {
20930            scheduleWritePackageRestrictionsLocked(userId);
20931            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20932            final long callingId = Binder.clearCallingIdentity();
20933            try {
20934                updateInstantAppInstallerLocked(packageName);
20935            } finally {
20936                Binder.restoreCallingIdentity(callingId);
20937            }
20938            components = mPendingBroadcasts.get(userId, packageName);
20939            final boolean newPackage = components == null;
20940            if (newPackage) {
20941                components = new ArrayList<String>();
20942            }
20943            if (!components.contains(componentName)) {
20944                components.add(componentName);
20945            }
20946            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20947                sendNow = true;
20948                // Purge entry from pending broadcast list if another one exists already
20949                // since we are sending one right away.
20950                mPendingBroadcasts.remove(userId, packageName);
20951            } else {
20952                if (newPackage) {
20953                    mPendingBroadcasts.put(userId, packageName, components);
20954                }
20955                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20956                    // Schedule a message
20957                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20958                }
20959            }
20960        }
20961
20962        long callingId = Binder.clearCallingIdentity();
20963        try {
20964            if (sendNow) {
20965                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20966                sendPackageChangedBroadcast(packageName,
20967                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20968            }
20969        } finally {
20970            Binder.restoreCallingIdentity(callingId);
20971        }
20972    }
20973
20974    @Override
20975    public void flushPackageRestrictionsAsUser(int userId) {
20976        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20977            return;
20978        }
20979        if (!sUserManager.exists(userId)) {
20980            return;
20981        }
20982        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20983                false /* checkShell */, "flushPackageRestrictions");
20984        synchronized (mPackages) {
20985            mSettings.writePackageRestrictionsLPr(userId);
20986            mDirtyUsers.remove(userId);
20987            if (mDirtyUsers.isEmpty()) {
20988                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20989            }
20990        }
20991    }
20992
20993    private void sendPackageChangedBroadcast(String packageName,
20994            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20995        if (DEBUG_INSTALL)
20996            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20997                    + componentNames);
20998        Bundle extras = new Bundle(4);
20999        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21000        String nameList[] = new String[componentNames.size()];
21001        componentNames.toArray(nameList);
21002        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21003        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21004        extras.putInt(Intent.EXTRA_UID, packageUid);
21005        // If this is not reporting a change of the overall package, then only send it
21006        // to registered receivers.  We don't want to launch a swath of apps for every
21007        // little component state change.
21008        final int flags = !componentNames.contains(packageName)
21009                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21010        final int userId = UserHandle.getUserId(packageUid);
21011        final boolean isInstantApp = isInstantApp(packageName, userId);
21012        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
21013        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
21014        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21015                userIds, instantUserIds);
21016    }
21017
21018    @Override
21019    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21020        if (!sUserManager.exists(userId)) return;
21021        final int callingUid = Binder.getCallingUid();
21022        if (getInstantAppPackageName(callingUid) != null) {
21023            return;
21024        }
21025        final int permission = mContext.checkCallingOrSelfPermission(
21026                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21027        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21028        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
21029                true /* requireFullPermission */, true /* checkShell */, "stop package");
21030        // writer
21031        synchronized (mPackages) {
21032            final PackageSetting ps = mSettings.mPackages.get(packageName);
21033            if (!filterAppAccessLPr(ps, callingUid, userId)
21034                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21035                            allowedByPermission, callingUid, userId)) {
21036                scheduleWritePackageRestrictionsLocked(userId);
21037            }
21038        }
21039    }
21040
21041    @Override
21042    public String getInstallerPackageName(String packageName) {
21043        final int callingUid = Binder.getCallingUid();
21044        synchronized (mPackages) {
21045            final PackageSetting ps = mSettings.mPackages.get(packageName);
21046            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21047                return null;
21048            }
21049            return mSettings.getInstallerPackageNameLPr(packageName);
21050        }
21051    }
21052
21053    public boolean isOrphaned(String packageName) {
21054        // reader
21055        synchronized (mPackages) {
21056            return mSettings.isOrphaned(packageName);
21057        }
21058    }
21059
21060    @Override
21061    public int getApplicationEnabledSetting(String packageName, int userId) {
21062        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21063        int callingUid = Binder.getCallingUid();
21064        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
21065                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21066        // reader
21067        synchronized (mPackages) {
21068            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21069                return COMPONENT_ENABLED_STATE_DISABLED;
21070            }
21071            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21072        }
21073    }
21074
21075    @Override
21076    public int getComponentEnabledSetting(ComponentName component, int userId) {
21077        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21078        int callingUid = Binder.getCallingUid();
21079        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
21080                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21081        synchronized (mPackages) {
21082            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21083                    component, TYPE_UNKNOWN, userId)) {
21084                return COMPONENT_ENABLED_STATE_DISABLED;
21085            }
21086            return mSettings.getComponentEnabledSettingLPr(component, userId);
21087        }
21088    }
21089
21090    @Override
21091    public void enterSafeMode() {
21092        enforceSystemOrRoot("Only the system can request entering safe mode");
21093
21094        if (!mSystemReady) {
21095            mSafeMode = true;
21096        }
21097    }
21098
21099    @Override
21100    public void systemReady() {
21101        enforceSystemOrRoot("Only the system can claim the system is ready");
21102
21103        mSystemReady = true;
21104        final ContentResolver resolver = mContext.getContentResolver();
21105        ContentObserver co = new ContentObserver(mHandler) {
21106            @Override
21107            public void onChange(boolean selfChange) {
21108                mWebInstantAppsDisabled =
21109                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21110                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21111            }
21112        };
21113        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21114                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21115                false, co, UserHandle.USER_SYSTEM);
21116        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure
21117                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21118        co.onChange(true);
21119
21120        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21121        // disabled after already being started.
21122        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21123                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21124
21125        // Read the compatibilty setting when the system is ready.
21126        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21127                mContext.getContentResolver(),
21128                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21129        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21130        if (DEBUG_SETTINGS) {
21131            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21132        }
21133
21134        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21135
21136        synchronized (mPackages) {
21137            // Verify that all of the preferred activity components actually
21138            // exist.  It is possible for applications to be updated and at
21139            // that point remove a previously declared activity component that
21140            // had been set as a preferred activity.  We try to clean this up
21141            // the next time we encounter that preferred activity, but it is
21142            // possible for the user flow to never be able to return to that
21143            // situation so here we do a sanity check to make sure we haven't
21144            // left any junk around.
21145            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21146            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21147                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21148                removed.clear();
21149                for (PreferredActivity pa : pir.filterSet()) {
21150                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21151                        removed.add(pa);
21152                    }
21153                }
21154                if (removed.size() > 0) {
21155                    for (int r=0; r<removed.size(); r++) {
21156                        PreferredActivity pa = removed.get(r);
21157                        Slog.w(TAG, "Removing dangling preferred activity: "
21158                                + pa.mPref.mComponent);
21159                        pir.removeFilter(pa);
21160                    }
21161                    mSettings.writePackageRestrictionsLPr(
21162                            mSettings.mPreferredActivities.keyAt(i));
21163                }
21164            }
21165
21166            for (int userId : UserManagerService.getInstance().getUserIds()) {
21167                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21168                    grantPermissionsUserIds = ArrayUtils.appendInt(
21169                            grantPermissionsUserIds, userId);
21170                }
21171            }
21172        }
21173        sUserManager.systemReady();
21174        // If we upgraded grant all default permissions before kicking off.
21175        for (int userId : grantPermissionsUserIds) {
21176            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21177        }
21178
21179        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21180            // If we did not grant default permissions, we preload from this the
21181            // default permission exceptions lazily to ensure we don't hit the
21182            // disk on a new user creation.
21183            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21184        }
21185
21186        // Now that we've scanned all packages, and granted any default
21187        // permissions, ensure permissions are updated. Beware of dragons if you
21188        // try optimizing this.
21189        synchronized (mPackages) {
21190            mPermissionManager.updateAllPermissions(
21191                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
21192                    mPermissionCallback);
21193        }
21194
21195        // Kick off any messages waiting for system ready
21196        if (mPostSystemReadyMessages != null) {
21197            for (Message msg : mPostSystemReadyMessages) {
21198                msg.sendToTarget();
21199            }
21200            mPostSystemReadyMessages = null;
21201        }
21202
21203        // Watch for external volumes that come and go over time
21204        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21205        storage.registerListener(mStorageListener);
21206
21207        mInstallerService.systemReady();
21208        mDexManager.systemReady();
21209        mPackageDexOptimizer.systemReady();
21210
21211        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21212                StorageManagerInternal.class);
21213        StorageManagerInternal.addExternalStoragePolicy(
21214                new StorageManagerInternal.ExternalStorageMountPolicy() {
21215            @Override
21216            public int getMountMode(int uid, String packageName) {
21217                if (Process.isIsolated(uid)) {
21218                    return Zygote.MOUNT_EXTERNAL_NONE;
21219                }
21220                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21221                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21222                }
21223                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21224                    return Zygote.MOUNT_EXTERNAL_READ;
21225                }
21226                return Zygote.MOUNT_EXTERNAL_WRITE;
21227            }
21228
21229            @Override
21230            public boolean hasExternalStorage(int uid, String packageName) {
21231                return true;
21232            }
21233        });
21234
21235        // Now that we're mostly running, clean up stale users and apps
21236        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21237        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21238
21239        mPermissionManager.systemReady();
21240
21241        if (mInstantAppResolverConnection != null) {
21242            mContext.registerReceiver(new BroadcastReceiver() {
21243                @Override
21244                public void onReceive(Context context, Intent intent) {
21245                    mInstantAppResolverConnection.optimisticBind();
21246                    mContext.unregisterReceiver(this);
21247                }
21248            }, new IntentFilter(Intent.ACTION_BOOT_COMPLETED));
21249        }
21250    }
21251
21252    public void waitForAppDataPrepared() {
21253        if (mPrepareAppDataFuture == null) {
21254            return;
21255        }
21256        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21257        mPrepareAppDataFuture = null;
21258    }
21259
21260    @Override
21261    public boolean isSafeMode() {
21262        // allow instant applications
21263        return mSafeMode;
21264    }
21265
21266    @Override
21267    public boolean hasSystemUidErrors() {
21268        // allow instant applications
21269        return mHasSystemUidErrors;
21270    }
21271
21272    static String arrayToString(int[] array) {
21273        StringBuffer buf = new StringBuffer(128);
21274        buf.append('[');
21275        if (array != null) {
21276            for (int i=0; i<array.length; i++) {
21277                if (i > 0) buf.append(", ");
21278                buf.append(array[i]);
21279            }
21280        }
21281        buf.append(']');
21282        return buf.toString();
21283    }
21284
21285    @Override
21286    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21287            FileDescriptor err, String[] args, ShellCallback callback,
21288            ResultReceiver resultReceiver) {
21289        (new PackageManagerShellCommand(this)).exec(
21290                this, in, out, err, args, callback, resultReceiver);
21291    }
21292
21293    @Override
21294    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21295        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21296
21297        DumpState dumpState = new DumpState();
21298        boolean fullPreferred = false;
21299        boolean checkin = false;
21300
21301        String packageName = null;
21302        ArraySet<String> permissionNames = null;
21303
21304        int opti = 0;
21305        while (opti < args.length) {
21306            String opt = args[opti];
21307            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21308                break;
21309            }
21310            opti++;
21311
21312            if ("-a".equals(opt)) {
21313                // Right now we only know how to print all.
21314            } else if ("-h".equals(opt)) {
21315                pw.println("Package manager dump options:");
21316                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21317                pw.println("    --checkin: dump for a checkin");
21318                pw.println("    -f: print details of intent filters");
21319                pw.println("    -h: print this help");
21320                pw.println("  cmd may be one of:");
21321                pw.println("    l[ibraries]: list known shared libraries");
21322                pw.println("    f[eatures]: list device features");
21323                pw.println("    k[eysets]: print known keysets");
21324                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21325                pw.println("    perm[issions]: dump permissions");
21326                pw.println("    permission [name ...]: dump declaration and use of given permission");
21327                pw.println("    pref[erred]: print preferred package settings");
21328                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21329                pw.println("    prov[iders]: dump content providers");
21330                pw.println("    p[ackages]: dump installed packages");
21331                pw.println("    s[hared-users]: dump shared user IDs");
21332                pw.println("    m[essages]: print collected runtime messages");
21333                pw.println("    v[erifiers]: print package verifier info");
21334                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21335                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21336                pw.println("    version: print database version info");
21337                pw.println("    write: write current settings now");
21338                pw.println("    installs: details about install sessions");
21339                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21340                pw.println("    dexopt: dump dexopt state");
21341                pw.println("    compiler-stats: dump compiler statistics");
21342                pw.println("    service-permissions: dump permissions required by services");
21343                pw.println("    <package.name>: info about given package");
21344                return;
21345            } else if ("--checkin".equals(opt)) {
21346                checkin = true;
21347            } else if ("-f".equals(opt)) {
21348                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21349            } else if ("--proto".equals(opt)) {
21350                dumpProto(fd);
21351                return;
21352            } else {
21353                pw.println("Unknown argument: " + opt + "; use -h for help");
21354            }
21355        }
21356
21357        // Is the caller requesting to dump a particular piece of data?
21358        if (opti < args.length) {
21359            String cmd = args[opti];
21360            opti++;
21361            // Is this a package name?
21362            if ("android".equals(cmd) || cmd.contains(".")) {
21363                packageName = cmd;
21364                // When dumping a single package, we always dump all of its
21365                // filter information since the amount of data will be reasonable.
21366                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21367            } else if ("check-permission".equals(cmd)) {
21368                if (opti >= args.length) {
21369                    pw.println("Error: check-permission missing permission argument");
21370                    return;
21371                }
21372                String perm = args[opti];
21373                opti++;
21374                if (opti >= args.length) {
21375                    pw.println("Error: check-permission missing package argument");
21376                    return;
21377                }
21378
21379                String pkg = args[opti];
21380                opti++;
21381                int user = UserHandle.getUserId(Binder.getCallingUid());
21382                if (opti < args.length) {
21383                    try {
21384                        user = Integer.parseInt(args[opti]);
21385                    } catch (NumberFormatException e) {
21386                        pw.println("Error: check-permission user argument is not a number: "
21387                                + args[opti]);
21388                        return;
21389                    }
21390                }
21391
21392                // Normalize package name to handle renamed packages and static libs
21393                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21394
21395                pw.println(checkPermission(perm, pkg, user));
21396                return;
21397            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21398                dumpState.setDump(DumpState.DUMP_LIBS);
21399            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21400                dumpState.setDump(DumpState.DUMP_FEATURES);
21401            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21402                if (opti >= args.length) {
21403                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21404                            | DumpState.DUMP_SERVICE_RESOLVERS
21405                            | DumpState.DUMP_RECEIVER_RESOLVERS
21406                            | DumpState.DUMP_CONTENT_RESOLVERS);
21407                } else {
21408                    while (opti < args.length) {
21409                        String name = args[opti];
21410                        if ("a".equals(name) || "activity".equals(name)) {
21411                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21412                        } else if ("s".equals(name) || "service".equals(name)) {
21413                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21414                        } else if ("r".equals(name) || "receiver".equals(name)) {
21415                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21416                        } else if ("c".equals(name) || "content".equals(name)) {
21417                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21418                        } else {
21419                            pw.println("Error: unknown resolver table type: " + name);
21420                            return;
21421                        }
21422                        opti++;
21423                    }
21424                }
21425            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21426                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21427            } else if ("permission".equals(cmd)) {
21428                if (opti >= args.length) {
21429                    pw.println("Error: permission requires permission name");
21430                    return;
21431                }
21432                permissionNames = new ArraySet<>();
21433                while (opti < args.length) {
21434                    permissionNames.add(args[opti]);
21435                    opti++;
21436                }
21437                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21438                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21439            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21440                dumpState.setDump(DumpState.DUMP_PREFERRED);
21441            } else if ("preferred-xml".equals(cmd)) {
21442                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21443                if (opti < args.length && "--full".equals(args[opti])) {
21444                    fullPreferred = true;
21445                    opti++;
21446                }
21447            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21448                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21449            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21450                dumpState.setDump(DumpState.DUMP_PACKAGES);
21451            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21452                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21453            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21454                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21455            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21456                dumpState.setDump(DumpState.DUMP_MESSAGES);
21457            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21458                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21459            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21460                    || "intent-filter-verifiers".equals(cmd)) {
21461                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21462            } else if ("version".equals(cmd)) {
21463                dumpState.setDump(DumpState.DUMP_VERSION);
21464            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21465                dumpState.setDump(DumpState.DUMP_KEYSETS);
21466            } else if ("installs".equals(cmd)) {
21467                dumpState.setDump(DumpState.DUMP_INSTALLS);
21468            } else if ("frozen".equals(cmd)) {
21469                dumpState.setDump(DumpState.DUMP_FROZEN);
21470            } else if ("volumes".equals(cmd)) {
21471                dumpState.setDump(DumpState.DUMP_VOLUMES);
21472            } else if ("dexopt".equals(cmd)) {
21473                dumpState.setDump(DumpState.DUMP_DEXOPT);
21474            } else if ("compiler-stats".equals(cmd)) {
21475                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21476            } else if ("changes".equals(cmd)) {
21477                dumpState.setDump(DumpState.DUMP_CHANGES);
21478            } else if ("service-permissions".equals(cmd)) {
21479                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
21480            } else if ("write".equals(cmd)) {
21481                synchronized (mPackages) {
21482                    mSettings.writeLPr();
21483                    pw.println("Settings written.");
21484                    return;
21485                }
21486            }
21487        }
21488
21489        if (checkin) {
21490            pw.println("vers,1");
21491        }
21492
21493        // reader
21494        synchronized (mPackages) {
21495            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21496                if (!checkin) {
21497                    if (dumpState.onTitlePrinted())
21498                        pw.println();
21499                    pw.println("Database versions:");
21500                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21501                }
21502            }
21503
21504            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21505                if (!checkin) {
21506                    if (dumpState.onTitlePrinted())
21507                        pw.println();
21508                    pw.println("Verifiers:");
21509                    pw.print("  Required: ");
21510                    pw.print(mRequiredVerifierPackage);
21511                    pw.print(" (uid=");
21512                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21513                            UserHandle.USER_SYSTEM));
21514                    pw.println(")");
21515                } else if (mRequiredVerifierPackage != null) {
21516                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21517                    pw.print(",");
21518                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21519                            UserHandle.USER_SYSTEM));
21520                }
21521            }
21522
21523            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21524                    packageName == null) {
21525                if (mIntentFilterVerifierComponent != null) {
21526                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21527                    if (!checkin) {
21528                        if (dumpState.onTitlePrinted())
21529                            pw.println();
21530                        pw.println("Intent Filter Verifier:");
21531                        pw.print("  Using: ");
21532                        pw.print(verifierPackageName);
21533                        pw.print(" (uid=");
21534                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21535                                UserHandle.USER_SYSTEM));
21536                        pw.println(")");
21537                    } else if (verifierPackageName != null) {
21538                        pw.print("ifv,"); pw.print(verifierPackageName);
21539                        pw.print(",");
21540                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21541                                UserHandle.USER_SYSTEM));
21542                    }
21543                } else {
21544                    pw.println();
21545                    pw.println("No Intent Filter Verifier available!");
21546                }
21547            }
21548
21549            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21550                boolean printedHeader = false;
21551                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21552                while (it.hasNext()) {
21553                    String libName = it.next();
21554                    LongSparseArray<SharedLibraryEntry> versionedLib
21555                            = mSharedLibraries.get(libName);
21556                    if (versionedLib == null) {
21557                        continue;
21558                    }
21559                    final int versionCount = versionedLib.size();
21560                    for (int i = 0; i < versionCount; i++) {
21561                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21562                        if (!checkin) {
21563                            if (!printedHeader) {
21564                                if (dumpState.onTitlePrinted())
21565                                    pw.println();
21566                                pw.println("Libraries:");
21567                                printedHeader = true;
21568                            }
21569                            pw.print("  ");
21570                        } else {
21571                            pw.print("lib,");
21572                        }
21573                        pw.print(libEntry.info.getName());
21574                        if (libEntry.info.isStatic()) {
21575                            pw.print(" version=" + libEntry.info.getLongVersion());
21576                        }
21577                        if (!checkin) {
21578                            pw.print(" -> ");
21579                        }
21580                        if (libEntry.path != null) {
21581                            pw.print(" (jar) ");
21582                            pw.print(libEntry.path);
21583                        } else {
21584                            pw.print(" (apk) ");
21585                            pw.print(libEntry.apk);
21586                        }
21587                        pw.println();
21588                    }
21589                }
21590            }
21591
21592            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21593                if (dumpState.onTitlePrinted())
21594                    pw.println();
21595                if (!checkin) {
21596                    pw.println("Features:");
21597                }
21598
21599                synchronized (mAvailableFeatures) {
21600                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21601                        if (checkin) {
21602                            pw.print("feat,");
21603                            pw.print(feat.name);
21604                            pw.print(",");
21605                            pw.println(feat.version);
21606                        } else {
21607                            pw.print("  ");
21608                            pw.print(feat.name);
21609                            if (feat.version > 0) {
21610                                pw.print(" version=");
21611                                pw.print(feat.version);
21612                            }
21613                            pw.println();
21614                        }
21615                    }
21616                }
21617            }
21618
21619            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21620                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21621                        : "Activity Resolver Table:", "  ", packageName,
21622                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21623                    dumpState.setTitlePrinted(true);
21624                }
21625            }
21626            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21627                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21628                        : "Receiver Resolver Table:", "  ", packageName,
21629                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21630                    dumpState.setTitlePrinted(true);
21631                }
21632            }
21633            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21634                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21635                        : "Service Resolver Table:", "  ", packageName,
21636                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21637                    dumpState.setTitlePrinted(true);
21638                }
21639            }
21640            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21641                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21642                        : "Provider Resolver Table:", "  ", packageName,
21643                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21644                    dumpState.setTitlePrinted(true);
21645                }
21646            }
21647
21648            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21649                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21650                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21651                    int user = mSettings.mPreferredActivities.keyAt(i);
21652                    if (pir.dump(pw,
21653                            dumpState.getTitlePrinted()
21654                                ? "\nPreferred Activities User " + user + ":"
21655                                : "Preferred Activities User " + user + ":", "  ",
21656                            packageName, true, false)) {
21657                        dumpState.setTitlePrinted(true);
21658                    }
21659                }
21660            }
21661
21662            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21663                pw.flush();
21664                FileOutputStream fout = new FileOutputStream(fd);
21665                BufferedOutputStream str = new BufferedOutputStream(fout);
21666                XmlSerializer serializer = new FastXmlSerializer();
21667                try {
21668                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21669                    serializer.startDocument(null, true);
21670                    serializer.setFeature(
21671                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21672                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21673                    serializer.endDocument();
21674                    serializer.flush();
21675                } catch (IllegalArgumentException e) {
21676                    pw.println("Failed writing: " + e);
21677                } catch (IllegalStateException e) {
21678                    pw.println("Failed writing: " + e);
21679                } catch (IOException e) {
21680                    pw.println("Failed writing: " + e);
21681                }
21682            }
21683
21684            if (!checkin
21685                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21686                    && packageName == null) {
21687                pw.println();
21688                int count = mSettings.mPackages.size();
21689                if (count == 0) {
21690                    pw.println("No applications!");
21691                    pw.println();
21692                } else {
21693                    final String prefix = "  ";
21694                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21695                    if (allPackageSettings.size() == 0) {
21696                        pw.println("No domain preferred apps!");
21697                        pw.println();
21698                    } else {
21699                        pw.println("App verification status:");
21700                        pw.println();
21701                        count = 0;
21702                        for (PackageSetting ps : allPackageSettings) {
21703                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21704                            if (ivi == null || ivi.getPackageName() == null) continue;
21705                            pw.println(prefix + "Package: " + ivi.getPackageName());
21706                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21707                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21708                            pw.println();
21709                            count++;
21710                        }
21711                        if (count == 0) {
21712                            pw.println(prefix + "No app verification established.");
21713                            pw.println();
21714                        }
21715                        for (int userId : sUserManager.getUserIds()) {
21716                            pw.println("App linkages for user " + userId + ":");
21717                            pw.println();
21718                            count = 0;
21719                            for (PackageSetting ps : allPackageSettings) {
21720                                final long status = ps.getDomainVerificationStatusForUser(userId);
21721                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21722                                        && !DEBUG_DOMAIN_VERIFICATION) {
21723                                    continue;
21724                                }
21725                                pw.println(prefix + "Package: " + ps.name);
21726                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21727                                String statusStr = IntentFilterVerificationInfo.
21728                                        getStatusStringFromValue(status);
21729                                pw.println(prefix + "Status:  " + statusStr);
21730                                pw.println();
21731                                count++;
21732                            }
21733                            if (count == 0) {
21734                                pw.println(prefix + "No configured app linkages.");
21735                                pw.println();
21736                            }
21737                        }
21738                    }
21739                }
21740            }
21741
21742            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21743                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21744            }
21745
21746            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21747                boolean printedSomething = false;
21748                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21749                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21750                        continue;
21751                    }
21752                    if (!printedSomething) {
21753                        if (dumpState.onTitlePrinted())
21754                            pw.println();
21755                        pw.println("Registered ContentProviders:");
21756                        printedSomething = true;
21757                    }
21758                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21759                    pw.print("    "); pw.println(p.toString());
21760                }
21761                printedSomething = false;
21762                for (Map.Entry<String, PackageParser.Provider> entry :
21763                        mProvidersByAuthority.entrySet()) {
21764                    PackageParser.Provider p = entry.getValue();
21765                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21766                        continue;
21767                    }
21768                    if (!printedSomething) {
21769                        if (dumpState.onTitlePrinted())
21770                            pw.println();
21771                        pw.println("ContentProvider Authorities:");
21772                        printedSomething = true;
21773                    }
21774                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21775                    pw.print("    "); pw.println(p.toString());
21776                    if (p.info != null && p.info.applicationInfo != null) {
21777                        final String appInfo = p.info.applicationInfo.toString();
21778                        pw.print("      applicationInfo="); pw.println(appInfo);
21779                    }
21780                }
21781            }
21782
21783            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21784                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21785            }
21786
21787            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21788                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21789            }
21790
21791            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21792                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21793            }
21794
21795            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21796                if (dumpState.onTitlePrinted()) pw.println();
21797                pw.println("Package Changes:");
21798                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21799                final int K = mChangedPackages.size();
21800                for (int i = 0; i < K; i++) {
21801                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21802                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21803                    final int N = changes.size();
21804                    if (N == 0) {
21805                        pw.print("    "); pw.println("No packages changed");
21806                    } else {
21807                        for (int j = 0; j < N; j++) {
21808                            final String pkgName = changes.valueAt(j);
21809                            final int sequenceNumber = changes.keyAt(j);
21810                            pw.print("    ");
21811                            pw.print("seq=");
21812                            pw.print(sequenceNumber);
21813                            pw.print(", package=");
21814                            pw.println(pkgName);
21815                        }
21816                    }
21817                }
21818            }
21819
21820            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21821                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21822            }
21823
21824            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21825                // XXX should handle packageName != null by dumping only install data that
21826                // the given package is involved with.
21827                if (dumpState.onTitlePrinted()) pw.println();
21828
21829                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21830                ipw.println();
21831                ipw.println("Frozen packages:");
21832                ipw.increaseIndent();
21833                if (mFrozenPackages.size() == 0) {
21834                    ipw.println("(none)");
21835                } else {
21836                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21837                        ipw.println(mFrozenPackages.valueAt(i));
21838                    }
21839                }
21840                ipw.decreaseIndent();
21841            }
21842
21843            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21844                if (dumpState.onTitlePrinted()) pw.println();
21845
21846                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21847                ipw.println();
21848                ipw.println("Loaded volumes:");
21849                ipw.increaseIndent();
21850                if (mLoadedVolumes.size() == 0) {
21851                    ipw.println("(none)");
21852                } else {
21853                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
21854                        ipw.println(mLoadedVolumes.valueAt(i));
21855                    }
21856                }
21857                ipw.decreaseIndent();
21858            }
21859
21860            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21861                    && packageName == null) {
21862                if (dumpState.onTitlePrinted()) pw.println();
21863                pw.println("Service permissions:");
21864
21865                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21866                while (filterIterator.hasNext()) {
21867                    final ServiceIntentInfo info = filterIterator.next();
21868                    final ServiceInfo serviceInfo = info.service.info;
21869                    final String permission = serviceInfo.permission;
21870                    if (permission != null) {
21871                        pw.print("    ");
21872                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21873                        pw.print(": ");
21874                        pw.println(permission);
21875                    }
21876                }
21877            }
21878
21879            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21880                if (dumpState.onTitlePrinted()) pw.println();
21881                dumpDexoptStateLPr(pw, packageName);
21882            }
21883
21884            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21885                if (dumpState.onTitlePrinted()) pw.println();
21886                dumpCompilerStatsLPr(pw, packageName);
21887            }
21888
21889            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21890                if (dumpState.onTitlePrinted()) pw.println();
21891                mSettings.dumpReadMessagesLPr(pw, dumpState);
21892
21893                pw.println();
21894                pw.println("Package warning messages:");
21895                dumpCriticalInfo(pw, null);
21896            }
21897
21898            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21899                dumpCriticalInfo(pw, "msg,");
21900            }
21901        }
21902
21903        // PackageInstaller should be called outside of mPackages lock
21904        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21905            // XXX should handle packageName != null by dumping only install data that
21906            // the given package is involved with.
21907            if (dumpState.onTitlePrinted()) pw.println();
21908            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21909        }
21910    }
21911
21912    private void dumpProto(FileDescriptor fd) {
21913        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21914
21915        synchronized (mPackages) {
21916            final long requiredVerifierPackageToken =
21917                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21918            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21919            proto.write(
21920                    PackageServiceDumpProto.PackageShortProto.UID,
21921                    getPackageUid(
21922                            mRequiredVerifierPackage,
21923                            MATCH_DEBUG_TRIAGED_MISSING,
21924                            UserHandle.USER_SYSTEM));
21925            proto.end(requiredVerifierPackageToken);
21926
21927            if (mIntentFilterVerifierComponent != null) {
21928                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21929                final long verifierPackageToken =
21930                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21931                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21932                proto.write(
21933                        PackageServiceDumpProto.PackageShortProto.UID,
21934                        getPackageUid(
21935                                verifierPackageName,
21936                                MATCH_DEBUG_TRIAGED_MISSING,
21937                                UserHandle.USER_SYSTEM));
21938                proto.end(verifierPackageToken);
21939            }
21940
21941            dumpSharedLibrariesProto(proto);
21942            dumpFeaturesProto(proto);
21943            mSettings.dumpPackagesProto(proto);
21944            mSettings.dumpSharedUsersProto(proto);
21945            dumpCriticalInfo(proto);
21946        }
21947        proto.flush();
21948    }
21949
21950    private void dumpFeaturesProto(ProtoOutputStream proto) {
21951        synchronized (mAvailableFeatures) {
21952            final int count = mAvailableFeatures.size();
21953            for (int i = 0; i < count; i++) {
21954                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21955            }
21956        }
21957    }
21958
21959    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21960        final int count = mSharedLibraries.size();
21961        for (int i = 0; i < count; i++) {
21962            final String libName = mSharedLibraries.keyAt(i);
21963            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21964            if (versionedLib == null) {
21965                continue;
21966            }
21967            final int versionCount = versionedLib.size();
21968            for (int j = 0; j < versionCount; j++) {
21969                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21970                final long sharedLibraryToken =
21971                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21972                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21973                final boolean isJar = (libEntry.path != null);
21974                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21975                if (isJar) {
21976                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21977                } else {
21978                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21979                }
21980                proto.end(sharedLibraryToken);
21981            }
21982        }
21983    }
21984
21985    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21986        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21987        ipw.println();
21988        ipw.println("Dexopt state:");
21989        ipw.increaseIndent();
21990        Collection<PackageParser.Package> packages = null;
21991        if (packageName != null) {
21992            PackageParser.Package targetPackage = mPackages.get(packageName);
21993            if (targetPackage != null) {
21994                packages = Collections.singletonList(targetPackage);
21995            } else {
21996                ipw.println("Unable to find package: " + packageName);
21997                return;
21998            }
21999        } else {
22000            packages = mPackages.values();
22001        }
22002
22003        for (PackageParser.Package pkg : packages) {
22004            ipw.println("[" + pkg.packageName + "]");
22005            ipw.increaseIndent();
22006            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
22007                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
22008            ipw.decreaseIndent();
22009        }
22010    }
22011
22012    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22013        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
22014        ipw.println();
22015        ipw.println("Compiler stats:");
22016        ipw.increaseIndent();
22017        Collection<PackageParser.Package> packages = null;
22018        if (packageName != null) {
22019            PackageParser.Package targetPackage = mPackages.get(packageName);
22020            if (targetPackage != null) {
22021                packages = Collections.singletonList(targetPackage);
22022            } else {
22023                ipw.println("Unable to find package: " + packageName);
22024                return;
22025            }
22026        } else {
22027            packages = mPackages.values();
22028        }
22029
22030        for (PackageParser.Package pkg : packages) {
22031            ipw.println("[" + pkg.packageName + "]");
22032            ipw.increaseIndent();
22033
22034            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22035            if (stats == null) {
22036                ipw.println("(No recorded stats)");
22037            } else {
22038                stats.dump(ipw);
22039            }
22040            ipw.decreaseIndent();
22041        }
22042    }
22043
22044    private String dumpDomainString(String packageName) {
22045        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22046                .getList();
22047        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22048
22049        ArraySet<String> result = new ArraySet<>();
22050        if (iviList.size() > 0) {
22051            for (IntentFilterVerificationInfo ivi : iviList) {
22052                for (String host : ivi.getDomains()) {
22053                    result.add(host);
22054                }
22055            }
22056        }
22057        if (filters != null && filters.size() > 0) {
22058            for (IntentFilter filter : filters) {
22059                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22060                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22061                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22062                    result.addAll(filter.getHostsList());
22063                }
22064            }
22065        }
22066
22067        StringBuilder sb = new StringBuilder(result.size() * 16);
22068        for (String domain : result) {
22069            if (sb.length() > 0) sb.append(" ");
22070            sb.append(domain);
22071        }
22072        return sb.toString();
22073    }
22074
22075    // ------- apps on sdcard specific code -------
22076    static final boolean DEBUG_SD_INSTALL = false;
22077
22078    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22079
22080    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22081
22082    private boolean mMediaMounted = false;
22083
22084    static String getEncryptKey() {
22085        try {
22086            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22087                    SD_ENCRYPTION_KEYSTORE_NAME);
22088            if (sdEncKey == null) {
22089                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22090                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22091                if (sdEncKey == null) {
22092                    Slog.e(TAG, "Failed to create encryption keys");
22093                    return null;
22094                }
22095            }
22096            return sdEncKey;
22097        } catch (NoSuchAlgorithmException nsae) {
22098            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22099            return null;
22100        } catch (IOException ioe) {
22101            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22102            return null;
22103        }
22104    }
22105
22106    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22107            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22108        final int size = infos.size();
22109        final String[] packageNames = new String[size];
22110        final int[] packageUids = new int[size];
22111        for (int i = 0; i < size; i++) {
22112            final ApplicationInfo info = infos.get(i);
22113            packageNames[i] = info.packageName;
22114            packageUids[i] = info.uid;
22115        }
22116        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22117                finishedReceiver);
22118    }
22119
22120    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22121            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22122        sendResourcesChangedBroadcast(mediaStatus, replacing,
22123                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22124    }
22125
22126    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22127            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22128        int size = pkgList.length;
22129        if (size > 0) {
22130            // Send broadcasts here
22131            Bundle extras = new Bundle();
22132            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22133            if (uidArr != null) {
22134                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22135            }
22136            if (replacing) {
22137                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22138            }
22139            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22140                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22141            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
22142        }
22143    }
22144
22145    private void loadPrivatePackages(final VolumeInfo vol) {
22146        mHandler.post(new Runnable() {
22147            @Override
22148            public void run() {
22149                loadPrivatePackagesInner(vol);
22150            }
22151        });
22152    }
22153
22154    private void loadPrivatePackagesInner(VolumeInfo vol) {
22155        final String volumeUuid = vol.fsUuid;
22156        if (TextUtils.isEmpty(volumeUuid)) {
22157            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22158            return;
22159        }
22160
22161        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22162        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22163        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22164
22165        final VersionInfo ver;
22166        final List<PackageSetting> packages;
22167        synchronized (mPackages) {
22168            ver = mSettings.findOrCreateVersion(volumeUuid);
22169            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22170        }
22171
22172        for (PackageSetting ps : packages) {
22173            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22174            synchronized (mInstallLock) {
22175                final PackageParser.Package pkg;
22176                try {
22177                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22178                    loaded.add(pkg.applicationInfo);
22179
22180                } catch (PackageManagerException e) {
22181                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22182                }
22183
22184                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22185                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22186                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22187                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22188                }
22189            }
22190        }
22191
22192        // Reconcile app data for all started/unlocked users
22193        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22194        final UserManager um = mContext.getSystemService(UserManager.class);
22195        UserManagerInternal umInternal = getUserManagerInternal();
22196        for (UserInfo user : um.getUsers()) {
22197            final int flags;
22198            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22199                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22200            } else if (umInternal.isUserRunning(user.id)) {
22201                flags = StorageManager.FLAG_STORAGE_DE;
22202            } else {
22203                continue;
22204            }
22205
22206            try {
22207                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22208                synchronized (mInstallLock) {
22209                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22210                }
22211            } catch (IllegalStateException e) {
22212                // Device was probably ejected, and we'll process that event momentarily
22213                Slog.w(TAG, "Failed to prepare storage: " + e);
22214            }
22215        }
22216
22217        synchronized (mPackages) {
22218            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
22219            if (sdkUpdated) {
22220                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22221                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22222            }
22223            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
22224                    mPermissionCallback);
22225
22226            // Yay, everything is now upgraded
22227            ver.forceCurrent();
22228
22229            mSettings.writeLPr();
22230        }
22231
22232        for (PackageFreezer freezer : freezers) {
22233            freezer.close();
22234        }
22235
22236        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22237        sendResourcesChangedBroadcast(true, false, loaded, null);
22238        mLoadedVolumes.add(vol.getId());
22239    }
22240
22241    private void unloadPrivatePackages(final VolumeInfo vol) {
22242        mHandler.post(new Runnable() {
22243            @Override
22244            public void run() {
22245                unloadPrivatePackagesInner(vol);
22246            }
22247        });
22248    }
22249
22250    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22251        final String volumeUuid = vol.fsUuid;
22252        if (TextUtils.isEmpty(volumeUuid)) {
22253            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22254            return;
22255        }
22256
22257        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22258        synchronized (mInstallLock) {
22259        synchronized (mPackages) {
22260            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22261            for (PackageSetting ps : packages) {
22262                if (ps.pkg == null) continue;
22263
22264                final ApplicationInfo info = ps.pkg.applicationInfo;
22265                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22266                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22267
22268                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22269                        "unloadPrivatePackagesInner")) {
22270                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22271                            false, null)) {
22272                        unloaded.add(info);
22273                    } else {
22274                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22275                    }
22276                }
22277
22278                // Try very hard to release any references to this package
22279                // so we don't risk the system server being killed due to
22280                // open FDs
22281                AttributeCache.instance().removePackage(ps.name);
22282            }
22283
22284            mSettings.writeLPr();
22285        }
22286        }
22287
22288        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22289        sendResourcesChangedBroadcast(false, false, unloaded, null);
22290        mLoadedVolumes.remove(vol.getId());
22291
22292        // Try very hard to release any references to this path so we don't risk
22293        // the system server being killed due to open FDs
22294        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
22295
22296        for (int i = 0; i < 3; i++) {
22297            System.gc();
22298            System.runFinalization();
22299        }
22300    }
22301
22302    private void assertPackageKnown(String volumeUuid, String packageName)
22303            throws PackageManagerException {
22304        synchronized (mPackages) {
22305            // Normalize package name to handle renamed packages
22306            packageName = normalizePackageNameLPr(packageName);
22307
22308            final PackageSetting ps = mSettings.mPackages.get(packageName);
22309            if (ps == null) {
22310                throw new PackageManagerException("Package " + packageName + " is unknown");
22311            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22312                throw new PackageManagerException(
22313                        "Package " + packageName + " found on unknown volume " + volumeUuid
22314                                + "; expected volume " + ps.volumeUuid);
22315            }
22316        }
22317    }
22318
22319    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22320            throws PackageManagerException {
22321        synchronized (mPackages) {
22322            // Normalize package name to handle renamed packages
22323            packageName = normalizePackageNameLPr(packageName);
22324
22325            final PackageSetting ps = mSettings.mPackages.get(packageName);
22326            if (ps == null) {
22327                throw new PackageManagerException("Package " + packageName + " is unknown");
22328            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22329                throw new PackageManagerException(
22330                        "Package " + packageName + " found on unknown volume " + volumeUuid
22331                                + "; expected volume " + ps.volumeUuid);
22332            } else if (!ps.getInstalled(userId)) {
22333                throw new PackageManagerException(
22334                        "Package " + packageName + " not installed for user " + userId);
22335            }
22336        }
22337    }
22338
22339    private List<String> collectAbsoluteCodePaths() {
22340        synchronized (mPackages) {
22341            List<String> codePaths = new ArrayList<>();
22342            final int packageCount = mSettings.mPackages.size();
22343            for (int i = 0; i < packageCount; i++) {
22344                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22345                codePaths.add(ps.codePath.getAbsolutePath());
22346            }
22347            return codePaths;
22348        }
22349    }
22350
22351    /**
22352     * Examine all apps present on given mounted volume, and destroy apps that
22353     * aren't expected, either due to uninstallation or reinstallation on
22354     * another volume.
22355     */
22356    private void reconcileApps(String volumeUuid) {
22357        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22358        List<File> filesToDelete = null;
22359
22360        final File[] files = FileUtils.listFilesOrEmpty(
22361                Environment.getDataAppDirectory(volumeUuid));
22362        for (File file : files) {
22363            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22364                    && !PackageInstallerService.isStageName(file.getName());
22365            if (!isPackage) {
22366                // Ignore entries which are not packages
22367                continue;
22368            }
22369
22370            String absolutePath = file.getAbsolutePath();
22371
22372            boolean pathValid = false;
22373            final int absoluteCodePathCount = absoluteCodePaths.size();
22374            for (int i = 0; i < absoluteCodePathCount; i++) {
22375                String absoluteCodePath = absoluteCodePaths.get(i);
22376                if (absolutePath.startsWith(absoluteCodePath)) {
22377                    pathValid = true;
22378                    break;
22379                }
22380            }
22381
22382            if (!pathValid) {
22383                if (filesToDelete == null) {
22384                    filesToDelete = new ArrayList<>();
22385                }
22386                filesToDelete.add(file);
22387            }
22388        }
22389
22390        if (filesToDelete != null) {
22391            final int fileToDeleteCount = filesToDelete.size();
22392            for (int i = 0; i < fileToDeleteCount; i++) {
22393                File fileToDelete = filesToDelete.get(i);
22394                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22395                synchronized (mInstallLock) {
22396                    removeCodePathLI(fileToDelete);
22397                }
22398            }
22399        }
22400    }
22401
22402    /**
22403     * Reconcile all app data for the given user.
22404     * <p>
22405     * Verifies that directories exist and that ownership and labeling is
22406     * correct for all installed apps on all mounted volumes.
22407     */
22408    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22409        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22410        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22411            final String volumeUuid = vol.getFsUuid();
22412            synchronized (mInstallLock) {
22413                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22414            }
22415        }
22416    }
22417
22418    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22419            boolean migrateAppData) {
22420        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22421    }
22422
22423    /**
22424     * Reconcile all app data on given mounted volume.
22425     * <p>
22426     * Destroys app data that isn't expected, either due to uninstallation or
22427     * reinstallation on another volume.
22428     * <p>
22429     * Verifies that directories exist and that ownership and labeling is
22430     * correct for all installed apps.
22431     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22432     */
22433    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22434            boolean migrateAppData, boolean onlyCoreApps) {
22435        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22436                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22437        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22438
22439        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22440        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22441
22442        // First look for stale data that doesn't belong, and check if things
22443        // have changed since we did our last restorecon
22444        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22445            if (StorageManager.isFileEncryptedNativeOrEmulated()
22446                    && !StorageManager.isUserKeyUnlocked(userId)) {
22447                throw new RuntimeException(
22448                        "Yikes, someone asked us to reconcile CE storage while " + userId
22449                                + " was still locked; this would have caused massive data loss!");
22450            }
22451
22452            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22453            for (File file : files) {
22454                final String packageName = file.getName();
22455                try {
22456                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22457                } catch (PackageManagerException e) {
22458                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22459                    try {
22460                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22461                                StorageManager.FLAG_STORAGE_CE, 0);
22462                    } catch (InstallerException e2) {
22463                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22464                    }
22465                }
22466            }
22467        }
22468        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22469            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22470            for (File file : files) {
22471                final String packageName = file.getName();
22472                try {
22473                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22474                } catch (PackageManagerException e) {
22475                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22476                    try {
22477                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22478                                StorageManager.FLAG_STORAGE_DE, 0);
22479                    } catch (InstallerException e2) {
22480                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22481                    }
22482                }
22483            }
22484        }
22485
22486        // Ensure that data directories are ready to roll for all packages
22487        // installed for this volume and user
22488        final List<PackageSetting> packages;
22489        synchronized (mPackages) {
22490            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22491        }
22492        int preparedCount = 0;
22493        for (PackageSetting ps : packages) {
22494            final String packageName = ps.name;
22495            if (ps.pkg == null) {
22496                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22497                // TODO: might be due to legacy ASEC apps; we should circle back
22498                // and reconcile again once they're scanned
22499                continue;
22500            }
22501            // Skip non-core apps if requested
22502            if (onlyCoreApps && !ps.pkg.coreApp) {
22503                result.add(packageName);
22504                continue;
22505            }
22506
22507            if (ps.getInstalled(userId)) {
22508                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22509                preparedCount++;
22510            }
22511        }
22512
22513        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22514        return result;
22515    }
22516
22517    /**
22518     * Prepare app data for the given app just after it was installed or
22519     * upgraded. This method carefully only touches users that it's installed
22520     * for, and it forces a restorecon to handle any seinfo changes.
22521     * <p>
22522     * Verifies that directories exist and that ownership and labeling is
22523     * correct for all installed apps. If there is an ownership mismatch, it
22524     * will try recovering system apps by wiping data; third-party app data is
22525     * left intact.
22526     * <p>
22527     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22528     */
22529    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22530        final PackageSetting ps;
22531        synchronized (mPackages) {
22532            ps = mSettings.mPackages.get(pkg.packageName);
22533            mSettings.writeKernelMappingLPr(ps);
22534        }
22535
22536        final UserManager um = mContext.getSystemService(UserManager.class);
22537        UserManagerInternal umInternal = getUserManagerInternal();
22538        for (UserInfo user : um.getUsers()) {
22539            final int flags;
22540            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22541                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22542            } else if (umInternal.isUserRunning(user.id)) {
22543                flags = StorageManager.FLAG_STORAGE_DE;
22544            } else {
22545                continue;
22546            }
22547
22548            if (ps.getInstalled(user.id)) {
22549                // TODO: when user data is locked, mark that we're still dirty
22550                prepareAppDataLIF(pkg, user.id, flags);
22551            }
22552        }
22553    }
22554
22555    /**
22556     * Prepare app data for the given app.
22557     * <p>
22558     * Verifies that directories exist and that ownership and labeling is
22559     * correct for all installed apps. If there is an ownership mismatch, this
22560     * will try recovering system apps by wiping data; third-party app data is
22561     * left intact.
22562     */
22563    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22564        if (pkg == null) {
22565            Slog.wtf(TAG, "Package was null!", new Throwable());
22566            return;
22567        }
22568        prepareAppDataLeafLIF(pkg, userId, flags);
22569        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22570        for (int i = 0; i < childCount; i++) {
22571            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22572        }
22573    }
22574
22575    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22576            boolean maybeMigrateAppData) {
22577        prepareAppDataLIF(pkg, userId, flags);
22578
22579        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22580            // We may have just shuffled around app data directories, so
22581            // prepare them one more time
22582            prepareAppDataLIF(pkg, userId, flags);
22583        }
22584    }
22585
22586    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22587        if (DEBUG_APP_DATA) {
22588            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22589                    + Integer.toHexString(flags));
22590        }
22591
22592        final PackageSetting ps;
22593        synchronized (mPackages) {
22594            ps = mSettings.mPackages.get(pkg.packageName);
22595        }
22596        final String volumeUuid = pkg.volumeUuid;
22597        final String packageName = pkg.packageName;
22598
22599        ApplicationInfo app = (ps == null)
22600                ? pkg.applicationInfo
22601                : PackageParser.generateApplicationInfo(pkg, 0, ps.readUserState(userId), userId);
22602        if (app == null) {
22603            app = pkg.applicationInfo;
22604        }
22605
22606        final int appId = UserHandle.getAppId(app.uid);
22607
22608        Preconditions.checkNotNull(app.seInfo);
22609
22610        final String seInfo = app.seInfo + (app.seInfoUser != null ? app.seInfoUser : "");
22611        long ceDataInode = -1;
22612        try {
22613            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22614                    appId, seInfo, app.targetSdkVersion);
22615        } catch (InstallerException e) {
22616            if (app.isSystemApp()) {
22617                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22618                        + ", but trying to recover: " + e);
22619                destroyAppDataLeafLIF(pkg, userId, flags);
22620                try {
22621                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22622                            appId, seInfo, app.targetSdkVersion);
22623                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22624                } catch (InstallerException e2) {
22625                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22626                }
22627            } else {
22628                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22629            }
22630        }
22631        // Prepare the application profiles only for upgrades and first boot (so that we don't
22632        // repeat the same operation at each boot).
22633        // We only have to cover the upgrade and first boot here because for app installs we
22634        // prepare the profiles before invoking dexopt (in installPackageLI).
22635        //
22636        // We also have to cover non system users because we do not call the usual install package
22637        // methods for them.
22638        if (mIsUpgrade || mFirstBoot || (userId != UserHandle.USER_SYSTEM)) {
22639            mArtManagerService.prepareAppProfiles(pkg, userId);
22640        }
22641
22642        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22643            // TODO: mark this structure as dirty so we persist it!
22644            synchronized (mPackages) {
22645                if (ps != null) {
22646                    ps.setCeDataInode(ceDataInode, userId);
22647                }
22648            }
22649        }
22650
22651        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22652    }
22653
22654    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22655        if (pkg == null) {
22656            Slog.wtf(TAG, "Package was null!", new Throwable());
22657            return;
22658        }
22659        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22660        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22661        for (int i = 0; i < childCount; i++) {
22662            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22663        }
22664    }
22665
22666    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22667        final String volumeUuid = pkg.volumeUuid;
22668        final String packageName = pkg.packageName;
22669        final ApplicationInfo app = pkg.applicationInfo;
22670
22671        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22672            // Create a native library symlink only if we have native libraries
22673            // and if the native libraries are 32 bit libraries. We do not provide
22674            // this symlink for 64 bit libraries.
22675            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22676                final String nativeLibPath = app.nativeLibraryDir;
22677                try {
22678                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22679                            nativeLibPath, userId);
22680                } catch (InstallerException e) {
22681                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22682                }
22683            }
22684        }
22685    }
22686
22687    /**
22688     * For system apps on non-FBE devices, this method migrates any existing
22689     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22690     * requested by the app.
22691     */
22692    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22693        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
22694                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22695            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22696                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22697            try {
22698                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22699                        storageTarget);
22700            } catch (InstallerException e) {
22701                logCriticalInfo(Log.WARN,
22702                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22703            }
22704            return true;
22705        } else {
22706            return false;
22707        }
22708    }
22709
22710    public PackageFreezer freezePackage(String packageName, String killReason) {
22711        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22712    }
22713
22714    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22715        return new PackageFreezer(packageName, userId, killReason);
22716    }
22717
22718    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22719            String killReason) {
22720        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22721    }
22722
22723    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22724            String killReason) {
22725        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22726            return new PackageFreezer();
22727        } else {
22728            return freezePackage(packageName, userId, killReason);
22729        }
22730    }
22731
22732    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22733            String killReason) {
22734        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22735    }
22736
22737    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22738            String killReason) {
22739        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22740            return new PackageFreezer();
22741        } else {
22742            return freezePackage(packageName, userId, killReason);
22743        }
22744    }
22745
22746    /**
22747     * Class that freezes and kills the given package upon creation, and
22748     * unfreezes it upon closing. This is typically used when doing surgery on
22749     * app code/data to prevent the app from running while you're working.
22750     */
22751    private class PackageFreezer implements AutoCloseable {
22752        private final String mPackageName;
22753        private final PackageFreezer[] mChildren;
22754
22755        private final boolean mWeFroze;
22756
22757        private final AtomicBoolean mClosed = new AtomicBoolean();
22758        private final CloseGuard mCloseGuard = CloseGuard.get();
22759
22760        /**
22761         * Create and return a stub freezer that doesn't actually do anything,
22762         * typically used when someone requested
22763         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22764         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22765         */
22766        public PackageFreezer() {
22767            mPackageName = null;
22768            mChildren = null;
22769            mWeFroze = false;
22770            mCloseGuard.open("close");
22771        }
22772
22773        public PackageFreezer(String packageName, int userId, String killReason) {
22774            synchronized (mPackages) {
22775                mPackageName = packageName;
22776                mWeFroze = mFrozenPackages.add(mPackageName);
22777
22778                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22779                if (ps != null) {
22780                    killApplication(ps.name, ps.appId, userId, killReason);
22781                }
22782
22783                final PackageParser.Package p = mPackages.get(packageName);
22784                if (p != null && p.childPackages != null) {
22785                    final int N = p.childPackages.size();
22786                    mChildren = new PackageFreezer[N];
22787                    for (int i = 0; i < N; i++) {
22788                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22789                                userId, killReason);
22790                    }
22791                } else {
22792                    mChildren = null;
22793                }
22794            }
22795            mCloseGuard.open("close");
22796        }
22797
22798        @Override
22799        protected void finalize() throws Throwable {
22800            try {
22801                if (mCloseGuard != null) {
22802                    mCloseGuard.warnIfOpen();
22803                }
22804
22805                close();
22806            } finally {
22807                super.finalize();
22808            }
22809        }
22810
22811        @Override
22812        public void close() {
22813            mCloseGuard.close();
22814            if (mClosed.compareAndSet(false, true)) {
22815                synchronized (mPackages) {
22816                    if (mWeFroze) {
22817                        mFrozenPackages.remove(mPackageName);
22818                    }
22819
22820                    if (mChildren != null) {
22821                        for (PackageFreezer freezer : mChildren) {
22822                            freezer.close();
22823                        }
22824                    }
22825                }
22826            }
22827        }
22828    }
22829
22830    /**
22831     * Verify that given package is currently frozen.
22832     */
22833    private void checkPackageFrozen(String packageName) {
22834        synchronized (mPackages) {
22835            if (!mFrozenPackages.contains(packageName)) {
22836                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22837            }
22838        }
22839    }
22840
22841    @Override
22842    public int movePackage(final String packageName, final String volumeUuid) {
22843        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22844
22845        final int callingUid = Binder.getCallingUid();
22846        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22847        final int moveId = mNextMoveId.getAndIncrement();
22848        mHandler.post(new Runnable() {
22849            @Override
22850            public void run() {
22851                try {
22852                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22853                } catch (PackageManagerException e) {
22854                    Slog.w(TAG, "Failed to move " + packageName, e);
22855                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22856                }
22857            }
22858        });
22859        return moveId;
22860    }
22861
22862    private void movePackageInternal(final String packageName, final String volumeUuid,
22863            final int moveId, final int callingUid, UserHandle user)
22864                    throws PackageManagerException {
22865        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22866        final PackageManager pm = mContext.getPackageManager();
22867
22868        final boolean currentAsec;
22869        final String currentVolumeUuid;
22870        final File codeFile;
22871        final String installerPackageName;
22872        final String packageAbiOverride;
22873        final int appId;
22874        final String seinfo;
22875        final String label;
22876        final int targetSdkVersion;
22877        final PackageFreezer freezer;
22878        final int[] installedUserIds;
22879
22880        // reader
22881        synchronized (mPackages) {
22882            final PackageParser.Package pkg = mPackages.get(packageName);
22883            final PackageSetting ps = mSettings.mPackages.get(packageName);
22884            if (pkg == null
22885                    || ps == null
22886                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22887                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22888            }
22889            if (pkg.applicationInfo.isSystemApp()) {
22890                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22891                        "Cannot move system application");
22892            }
22893
22894            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22895            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22896                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22897            if (isInternalStorage && !allow3rdPartyOnInternal) {
22898                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22899                        "3rd party apps are not allowed on internal storage");
22900            }
22901
22902            if (pkg.applicationInfo.isExternalAsec()) {
22903                currentAsec = true;
22904                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22905            } else if (pkg.applicationInfo.isForwardLocked()) {
22906                currentAsec = true;
22907                currentVolumeUuid = "forward_locked";
22908            } else {
22909                currentAsec = false;
22910                currentVolumeUuid = ps.volumeUuid;
22911
22912                final File probe = new File(pkg.codePath);
22913                final File probeOat = new File(probe, "oat");
22914                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22915                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22916                            "Move only supported for modern cluster style installs");
22917                }
22918            }
22919
22920            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22921                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22922                        "Package already moved to " + volumeUuid);
22923            }
22924            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22925                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22926                        "Device admin cannot be moved");
22927            }
22928
22929            if (mFrozenPackages.contains(packageName)) {
22930                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22931                        "Failed to move already frozen package");
22932            }
22933
22934            codeFile = new File(pkg.codePath);
22935            installerPackageName = ps.installerPackageName;
22936            packageAbiOverride = ps.cpuAbiOverrideString;
22937            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22938            seinfo = pkg.applicationInfo.seInfo;
22939            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22940            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22941            freezer = freezePackage(packageName, "movePackageInternal");
22942            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22943        }
22944
22945        final Bundle extras = new Bundle();
22946        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22947        extras.putString(Intent.EXTRA_TITLE, label);
22948        mMoveCallbacks.notifyCreated(moveId, extras);
22949
22950        int installFlags;
22951        final boolean moveCompleteApp;
22952        final File measurePath;
22953
22954        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22955            installFlags = INSTALL_INTERNAL;
22956            moveCompleteApp = !currentAsec;
22957            measurePath = Environment.getDataAppDirectory(volumeUuid);
22958        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22959            installFlags = INSTALL_EXTERNAL;
22960            moveCompleteApp = false;
22961            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22962        } else {
22963            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22964            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22965                    || !volume.isMountedWritable()) {
22966                freezer.close();
22967                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22968                        "Move location not mounted private volume");
22969            }
22970
22971            Preconditions.checkState(!currentAsec);
22972
22973            installFlags = INSTALL_INTERNAL;
22974            moveCompleteApp = true;
22975            measurePath = Environment.getDataAppDirectory(volumeUuid);
22976        }
22977
22978        // If we're moving app data around, we need all the users unlocked
22979        if (moveCompleteApp) {
22980            for (int userId : installedUserIds) {
22981                if (StorageManager.isFileEncryptedNativeOrEmulated()
22982                        && !StorageManager.isUserKeyUnlocked(userId)) {
22983                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22984                            "User " + userId + " must be unlocked");
22985                }
22986            }
22987        }
22988
22989        final PackageStats stats = new PackageStats(null, -1);
22990        synchronized (mInstaller) {
22991            for (int userId : installedUserIds) {
22992                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22993                    freezer.close();
22994                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22995                            "Failed to measure package size");
22996                }
22997            }
22998        }
22999
23000        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23001                + stats.dataSize);
23002
23003        final long startFreeBytes = measurePath.getUsableSpace();
23004        final long sizeBytes;
23005        if (moveCompleteApp) {
23006            sizeBytes = stats.codeSize + stats.dataSize;
23007        } else {
23008            sizeBytes = stats.codeSize;
23009        }
23010
23011        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23012            freezer.close();
23013            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23014                    "Not enough free space to move");
23015        }
23016
23017        mMoveCallbacks.notifyStatusChanged(moveId, 10);
23018
23019        final CountDownLatch installedLatch = new CountDownLatch(1);
23020        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23021            @Override
23022            public void onUserActionRequired(Intent intent) throws RemoteException {
23023                throw new IllegalStateException();
23024            }
23025
23026            @Override
23027            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23028                    Bundle extras) throws RemoteException {
23029                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23030                        + PackageManager.installStatusToString(returnCode, msg));
23031
23032                installedLatch.countDown();
23033                freezer.close();
23034
23035                final int status = PackageManager.installStatusToPublicStatus(returnCode);
23036                switch (status) {
23037                    case PackageInstaller.STATUS_SUCCESS:
23038                        mMoveCallbacks.notifyStatusChanged(moveId,
23039                                PackageManager.MOVE_SUCCEEDED);
23040                        break;
23041                    case PackageInstaller.STATUS_FAILURE_STORAGE:
23042                        mMoveCallbacks.notifyStatusChanged(moveId,
23043                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23044                        break;
23045                    default:
23046                        mMoveCallbacks.notifyStatusChanged(moveId,
23047                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23048                        break;
23049                }
23050            }
23051        };
23052
23053        final MoveInfo move;
23054        if (moveCompleteApp) {
23055            // Kick off a thread to report progress estimates
23056            new Thread() {
23057                @Override
23058                public void run() {
23059                    while (true) {
23060                        try {
23061                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
23062                                break;
23063                            }
23064                        } catch (InterruptedException ignored) {
23065                        }
23066
23067                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23068                        final int progress = 10 + (int) MathUtils.constrain(
23069                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23070                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
23071                    }
23072                }
23073            }.start();
23074
23075            final String dataAppName = codeFile.getName();
23076            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23077                    dataAppName, appId, seinfo, targetSdkVersion);
23078        } else {
23079            move = null;
23080        }
23081
23082        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23083
23084        final Message msg = mHandler.obtainMessage(INIT_COPY);
23085        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23086        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23087                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23088                packageAbiOverride, null /*grantedPermissions*/,
23089                PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
23090        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23091        msg.obj = params;
23092
23093        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23094                System.identityHashCode(msg.obj));
23095        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23096                System.identityHashCode(msg.obj));
23097
23098        mHandler.sendMessage(msg);
23099    }
23100
23101    @Override
23102    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23103        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23104
23105        final int realMoveId = mNextMoveId.getAndIncrement();
23106        final Bundle extras = new Bundle();
23107        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23108        mMoveCallbacks.notifyCreated(realMoveId, extras);
23109
23110        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23111            @Override
23112            public void onCreated(int moveId, Bundle extras) {
23113                // Ignored
23114            }
23115
23116            @Override
23117            public void onStatusChanged(int moveId, int status, long estMillis) {
23118                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23119            }
23120        };
23121
23122        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23123        storage.setPrimaryStorageUuid(volumeUuid, callback);
23124        return realMoveId;
23125    }
23126
23127    @Override
23128    public int getMoveStatus(int moveId) {
23129        mContext.enforceCallingOrSelfPermission(
23130                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23131        return mMoveCallbacks.mLastStatus.get(moveId);
23132    }
23133
23134    @Override
23135    public void registerMoveCallback(IPackageMoveObserver callback) {
23136        mContext.enforceCallingOrSelfPermission(
23137                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23138        mMoveCallbacks.register(callback);
23139    }
23140
23141    @Override
23142    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23143        mContext.enforceCallingOrSelfPermission(
23144                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23145        mMoveCallbacks.unregister(callback);
23146    }
23147
23148    @Override
23149    public boolean setInstallLocation(int loc) {
23150        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23151                null);
23152        if (getInstallLocation() == loc) {
23153            return true;
23154        }
23155        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23156                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23157            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23158                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23159            return true;
23160        }
23161        return false;
23162   }
23163
23164    @Override
23165    public int getInstallLocation() {
23166        // allow instant app access
23167        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23168                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23169                PackageHelper.APP_INSTALL_AUTO);
23170    }
23171
23172    /** Called by UserManagerService */
23173    void cleanUpUser(UserManagerService userManager, int userHandle) {
23174        synchronized (mPackages) {
23175            mDirtyUsers.remove(userHandle);
23176            mUserNeedsBadging.delete(userHandle);
23177            mSettings.removeUserLPw(userHandle);
23178            mPendingBroadcasts.remove(userHandle);
23179            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23180            removeUnusedPackagesLPw(userManager, userHandle);
23181        }
23182    }
23183
23184    /**
23185     * We're removing userHandle and would like to remove any downloaded packages
23186     * that are no longer in use by any other user.
23187     * @param userHandle the user being removed
23188     */
23189    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23190        final boolean DEBUG_CLEAN_APKS = false;
23191        int [] users = userManager.getUserIds();
23192        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23193        while (psit.hasNext()) {
23194            PackageSetting ps = psit.next();
23195            if (ps.pkg == null) {
23196                continue;
23197            }
23198            final String packageName = ps.pkg.packageName;
23199            // Skip over if system app
23200            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23201                continue;
23202            }
23203            if (DEBUG_CLEAN_APKS) {
23204                Slog.i(TAG, "Checking package " + packageName);
23205            }
23206            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23207            if (keep) {
23208                if (DEBUG_CLEAN_APKS) {
23209                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23210                }
23211            } else {
23212                for (int i = 0; i < users.length; i++) {
23213                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23214                        keep = true;
23215                        if (DEBUG_CLEAN_APKS) {
23216                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23217                                    + users[i]);
23218                        }
23219                        break;
23220                    }
23221                }
23222            }
23223            if (!keep) {
23224                if (DEBUG_CLEAN_APKS) {
23225                    Slog.i(TAG, "  Removing package " + packageName);
23226                }
23227                mHandler.post(new Runnable() {
23228                    public void run() {
23229                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23230                                userHandle, 0);
23231                    } //end run
23232                });
23233            }
23234        }
23235    }
23236
23237    /** Called by UserManagerService */
23238    void createNewUser(int userId, String[] disallowedPackages) {
23239        synchronized (mInstallLock) {
23240            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23241        }
23242        synchronized (mPackages) {
23243            scheduleWritePackageRestrictionsLocked(userId);
23244            scheduleWritePackageListLocked(userId);
23245            applyFactoryDefaultBrowserLPw(userId);
23246            primeDomainVerificationsLPw(userId);
23247        }
23248    }
23249
23250    void onNewUserCreated(final int userId) {
23251        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23252        synchronized(mPackages) {
23253            // If permission review for legacy apps is required, we represent
23254            // dagerous permissions for such apps as always granted runtime
23255            // permissions to keep per user flag state whether review is needed.
23256            // Hence, if a new user is added we have to propagate dangerous
23257            // permission grants for these legacy apps.
23258            if (mSettings.mPermissions.mPermissionReviewRequired) {
23259// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
23260                mPermissionManager.updateAllPermissions(
23261                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
23262                        mPermissionCallback);
23263            }
23264        }
23265    }
23266
23267    @Override
23268    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23269        mContext.enforceCallingOrSelfPermission(
23270                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23271                "Only package verification agents can read the verifier device identity");
23272
23273        synchronized (mPackages) {
23274            return mSettings.getVerifierDeviceIdentityLPw();
23275        }
23276    }
23277
23278    @Override
23279    public void setPermissionEnforced(String permission, boolean enforced) {
23280        // TODO: Now that we no longer change GID for storage, this should to away.
23281        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23282                "setPermissionEnforced");
23283        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23284            synchronized (mPackages) {
23285                if (mSettings.mReadExternalStorageEnforced == null
23286                        || mSettings.mReadExternalStorageEnforced != enforced) {
23287                    mSettings.mReadExternalStorageEnforced =
23288                            enforced ? Boolean.TRUE : Boolean.FALSE;
23289                    mSettings.writeLPr();
23290                }
23291            }
23292            // kill any non-foreground processes so we restart them and
23293            // grant/revoke the GID.
23294            final IActivityManager am = ActivityManager.getService();
23295            if (am != null) {
23296                final long token = Binder.clearCallingIdentity();
23297                try {
23298                    am.killProcessesBelowForeground("setPermissionEnforcement");
23299                } catch (RemoteException e) {
23300                } finally {
23301                    Binder.restoreCallingIdentity(token);
23302                }
23303            }
23304        } else {
23305            throw new IllegalArgumentException("No selective enforcement for " + permission);
23306        }
23307    }
23308
23309    @Override
23310    @Deprecated
23311    public boolean isPermissionEnforced(String permission) {
23312        // allow instant applications
23313        return true;
23314    }
23315
23316    @Override
23317    public boolean isStorageLow() {
23318        // allow instant applications
23319        final long token = Binder.clearCallingIdentity();
23320        try {
23321            final DeviceStorageMonitorInternal
23322                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23323            if (dsm != null) {
23324                return dsm.isMemoryLow();
23325            } else {
23326                return false;
23327            }
23328        } finally {
23329            Binder.restoreCallingIdentity(token);
23330        }
23331    }
23332
23333    @Override
23334    public IPackageInstaller getPackageInstaller() {
23335        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23336            return null;
23337        }
23338        return mInstallerService;
23339    }
23340
23341    @Override
23342    public IArtManager getArtManager() {
23343        return mArtManagerService;
23344    }
23345
23346    private boolean userNeedsBadging(int userId) {
23347        int index = mUserNeedsBadging.indexOfKey(userId);
23348        if (index < 0) {
23349            final UserInfo userInfo;
23350            final long token = Binder.clearCallingIdentity();
23351            try {
23352                userInfo = sUserManager.getUserInfo(userId);
23353            } finally {
23354                Binder.restoreCallingIdentity(token);
23355            }
23356            final boolean b;
23357            if (userInfo != null && userInfo.isManagedProfile()) {
23358                b = true;
23359            } else {
23360                b = false;
23361            }
23362            mUserNeedsBadging.put(userId, b);
23363            return b;
23364        }
23365        return mUserNeedsBadging.valueAt(index);
23366    }
23367
23368    @Override
23369    public KeySet getKeySetByAlias(String packageName, String alias) {
23370        if (packageName == null || alias == null) {
23371            return null;
23372        }
23373        synchronized(mPackages) {
23374            final PackageParser.Package pkg = mPackages.get(packageName);
23375            if (pkg == null) {
23376                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23377                throw new IllegalArgumentException("Unknown package: " + packageName);
23378            }
23379            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23380            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
23381                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
23382                throw new IllegalArgumentException("Unknown package: " + packageName);
23383            }
23384            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23385            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23386        }
23387    }
23388
23389    @Override
23390    public KeySet getSigningKeySet(String packageName) {
23391        if (packageName == null) {
23392            return null;
23393        }
23394        synchronized(mPackages) {
23395            final int callingUid = Binder.getCallingUid();
23396            final int callingUserId = UserHandle.getUserId(callingUid);
23397            final PackageParser.Package pkg = mPackages.get(packageName);
23398            if (pkg == null) {
23399                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23400                throw new IllegalArgumentException("Unknown package: " + packageName);
23401            }
23402            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23403            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23404                // filter and pretend the package doesn't exist
23405                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23406                        + ", uid:" + callingUid);
23407                throw new IllegalArgumentException("Unknown package: " + packageName);
23408            }
23409            if (pkg.applicationInfo.uid != callingUid
23410                    && Process.SYSTEM_UID != callingUid) {
23411                throw new SecurityException("May not access signing KeySet of other apps.");
23412            }
23413            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23414            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23415        }
23416    }
23417
23418    @Override
23419    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23420        final int callingUid = Binder.getCallingUid();
23421        if (getInstantAppPackageName(callingUid) != null) {
23422            return false;
23423        }
23424        if (packageName == null || ks == null) {
23425            return false;
23426        }
23427        synchronized(mPackages) {
23428            final PackageParser.Package pkg = mPackages.get(packageName);
23429            if (pkg == null
23430                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23431                            UserHandle.getUserId(callingUid))) {
23432                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23433                throw new IllegalArgumentException("Unknown package: " + packageName);
23434            }
23435            IBinder ksh = ks.getToken();
23436            if (ksh instanceof KeySetHandle) {
23437                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23438                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23439            }
23440            return false;
23441        }
23442    }
23443
23444    @Override
23445    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23446        final int callingUid = Binder.getCallingUid();
23447        if (getInstantAppPackageName(callingUid) != null) {
23448            return false;
23449        }
23450        if (packageName == null || ks == null) {
23451            return false;
23452        }
23453        synchronized(mPackages) {
23454            final PackageParser.Package pkg = mPackages.get(packageName);
23455            if (pkg == null
23456                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23457                            UserHandle.getUserId(callingUid))) {
23458                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23459                throw new IllegalArgumentException("Unknown package: " + packageName);
23460            }
23461            IBinder ksh = ks.getToken();
23462            if (ksh instanceof KeySetHandle) {
23463                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23464                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23465            }
23466            return false;
23467        }
23468    }
23469
23470    private void deletePackageIfUnusedLPr(final String packageName) {
23471        PackageSetting ps = mSettings.mPackages.get(packageName);
23472        if (ps == null) {
23473            return;
23474        }
23475        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23476            // TODO Implement atomic delete if package is unused
23477            // It is currently possible that the package will be deleted even if it is installed
23478            // after this method returns.
23479            mHandler.post(new Runnable() {
23480                public void run() {
23481                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23482                            0, PackageManager.DELETE_ALL_USERS);
23483                }
23484            });
23485        }
23486    }
23487
23488    /**
23489     * Check and throw if the given before/after packages would be considered a
23490     * downgrade.
23491     */
23492    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23493            throws PackageManagerException {
23494        if (after.getLongVersionCode() < before.getLongVersionCode()) {
23495            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23496                    "Update version code " + after.versionCode + " is older than current "
23497                    + before.getLongVersionCode());
23498        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
23499            if (after.baseRevisionCode < before.baseRevisionCode) {
23500                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23501                        "Update base revision code " + after.baseRevisionCode
23502                        + " is older than current " + before.baseRevisionCode);
23503            }
23504
23505            if (!ArrayUtils.isEmpty(after.splitNames)) {
23506                for (int i = 0; i < after.splitNames.length; i++) {
23507                    final String splitName = after.splitNames[i];
23508                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23509                    if (j != -1) {
23510                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23511                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23512                                    "Update split " + splitName + " revision code "
23513                                    + after.splitRevisionCodes[i] + " is older than current "
23514                                    + before.splitRevisionCodes[j]);
23515                        }
23516                    }
23517                }
23518            }
23519        }
23520    }
23521
23522    private static class MoveCallbacks extends Handler {
23523        private static final int MSG_CREATED = 1;
23524        private static final int MSG_STATUS_CHANGED = 2;
23525
23526        private final RemoteCallbackList<IPackageMoveObserver>
23527                mCallbacks = new RemoteCallbackList<>();
23528
23529        private final SparseIntArray mLastStatus = new SparseIntArray();
23530
23531        public MoveCallbacks(Looper looper) {
23532            super(looper);
23533        }
23534
23535        public void register(IPackageMoveObserver callback) {
23536            mCallbacks.register(callback);
23537        }
23538
23539        public void unregister(IPackageMoveObserver callback) {
23540            mCallbacks.unregister(callback);
23541        }
23542
23543        @Override
23544        public void handleMessage(Message msg) {
23545            final SomeArgs args = (SomeArgs) msg.obj;
23546            final int n = mCallbacks.beginBroadcast();
23547            for (int i = 0; i < n; i++) {
23548                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23549                try {
23550                    invokeCallback(callback, msg.what, args);
23551                } catch (RemoteException ignored) {
23552                }
23553            }
23554            mCallbacks.finishBroadcast();
23555            args.recycle();
23556        }
23557
23558        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23559                throws RemoteException {
23560            switch (what) {
23561                case MSG_CREATED: {
23562                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23563                    break;
23564                }
23565                case MSG_STATUS_CHANGED: {
23566                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23567                    break;
23568                }
23569            }
23570        }
23571
23572        private void notifyCreated(int moveId, Bundle extras) {
23573            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23574
23575            final SomeArgs args = SomeArgs.obtain();
23576            args.argi1 = moveId;
23577            args.arg2 = extras;
23578            obtainMessage(MSG_CREATED, args).sendToTarget();
23579        }
23580
23581        private void notifyStatusChanged(int moveId, int status) {
23582            notifyStatusChanged(moveId, status, -1);
23583        }
23584
23585        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23586            Slog.v(TAG, "Move " + moveId + " status " + status);
23587
23588            final SomeArgs args = SomeArgs.obtain();
23589            args.argi1 = moveId;
23590            args.argi2 = status;
23591            args.arg3 = estMillis;
23592            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23593
23594            synchronized (mLastStatus) {
23595                mLastStatus.put(moveId, status);
23596            }
23597        }
23598    }
23599
23600    private final static class OnPermissionChangeListeners extends Handler {
23601        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23602
23603        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23604                new RemoteCallbackList<>();
23605
23606        public OnPermissionChangeListeners(Looper looper) {
23607            super(looper);
23608        }
23609
23610        @Override
23611        public void handleMessage(Message msg) {
23612            switch (msg.what) {
23613                case MSG_ON_PERMISSIONS_CHANGED: {
23614                    final int uid = msg.arg1;
23615                    handleOnPermissionsChanged(uid);
23616                } break;
23617            }
23618        }
23619
23620        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23621            mPermissionListeners.register(listener);
23622
23623        }
23624
23625        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23626            mPermissionListeners.unregister(listener);
23627        }
23628
23629        public void onPermissionsChanged(int uid) {
23630            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23631                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23632            }
23633        }
23634
23635        private void handleOnPermissionsChanged(int uid) {
23636            final int count = mPermissionListeners.beginBroadcast();
23637            try {
23638                for (int i = 0; i < count; i++) {
23639                    IOnPermissionsChangeListener callback = mPermissionListeners
23640                            .getBroadcastItem(i);
23641                    try {
23642                        callback.onPermissionsChanged(uid);
23643                    } catch (RemoteException e) {
23644                        Log.e(TAG, "Permission listener is dead", e);
23645                    }
23646                }
23647            } finally {
23648                mPermissionListeners.finishBroadcast();
23649            }
23650        }
23651    }
23652
23653    private class PackageManagerNative extends IPackageManagerNative.Stub {
23654        @Override
23655        public String[] getNamesForUids(int[] uids) throws RemoteException {
23656            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23657            // massage results so they can be parsed by the native binder
23658            for (int i = results.length - 1; i >= 0; --i) {
23659                if (results[i] == null) {
23660                    results[i] = "";
23661                }
23662            }
23663            return results;
23664        }
23665
23666        // NB: this differentiates between preloads and sideloads
23667        @Override
23668        public String getInstallerForPackage(String packageName) throws RemoteException {
23669            final String installerName = getInstallerPackageName(packageName);
23670            if (!TextUtils.isEmpty(installerName)) {
23671                return installerName;
23672            }
23673            // differentiate between preload and sideload
23674            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23675            ApplicationInfo appInfo = getApplicationInfo(packageName,
23676                                    /*flags*/ 0,
23677                                    /*userId*/ callingUser);
23678            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23679                return "preload";
23680            }
23681            return "";
23682        }
23683
23684        @Override
23685        public long getVersionCodeForPackage(String packageName) throws RemoteException {
23686            try {
23687                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23688                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23689                if (pInfo != null) {
23690                    return pInfo.getLongVersionCode();
23691                }
23692            } catch (Exception e) {
23693            }
23694            return 0;
23695        }
23696    }
23697
23698    private class PackageManagerInternalImpl extends PackageManagerInternal {
23699        @Override
23700        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23701                int flagValues, int userId) {
23702            PackageManagerService.this.updatePermissionFlags(
23703                    permName, packageName, flagMask, flagValues, userId);
23704        }
23705
23706        @Override
23707        public boolean isDataRestoreSafe(byte[] restoringFromSigHash, String packageName) {
23708            SigningDetails sd = getSigningDetails(packageName);
23709            if (sd == null) {
23710                return false;
23711            }
23712            return sd.hasSha256Certificate(restoringFromSigHash,
23713                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23714        }
23715
23716        @Override
23717        public boolean isDataRestoreSafe(Signature restoringFromSig, String packageName) {
23718            SigningDetails sd = getSigningDetails(packageName);
23719            if (sd == null) {
23720                return false;
23721            }
23722            return sd.hasCertificate(restoringFromSig,
23723                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23724        }
23725
23726        @Override
23727        public boolean hasSignatureCapability(int serverUid, int clientUid,
23728                @SigningDetails.CertCapabilities int capability) {
23729            SigningDetails serverSigningDetails = getSigningDetails(serverUid);
23730            SigningDetails clientSigningDetails = getSigningDetails(clientUid);
23731            return serverSigningDetails.checkCapability(clientSigningDetails, capability)
23732                    || clientSigningDetails.hasAncestorOrSelf(serverSigningDetails);
23733
23734        }
23735
23736        private SigningDetails getSigningDetails(@NonNull String packageName) {
23737            synchronized (mPackages) {
23738                PackageParser.Package p = mPackages.get(packageName);
23739                if (p == null) {
23740                    return null;
23741                }
23742                return p.mSigningDetails;
23743            }
23744        }
23745
23746        private SigningDetails getSigningDetails(int uid) {
23747            synchronized (mPackages) {
23748                final int appId = UserHandle.getAppId(uid);
23749                final Object obj = mSettings.getUserIdLPr(appId);
23750                if (obj != null) {
23751                    if (obj instanceof SharedUserSetting) {
23752                        return ((SharedUserSetting) obj).signatures.mSigningDetails;
23753                    } else if (obj instanceof PackageSetting) {
23754                        final PackageSetting ps = (PackageSetting) obj;
23755                        return ps.signatures.mSigningDetails;
23756                    }
23757                }
23758                return SigningDetails.UNKNOWN;
23759            }
23760        }
23761
23762        @Override
23763        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23764            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23765        }
23766
23767        @Override
23768        public boolean isInstantApp(String packageName, int userId) {
23769            return PackageManagerService.this.isInstantApp(packageName, userId);
23770        }
23771
23772        @Override
23773        public String getInstantAppPackageName(int uid) {
23774            return PackageManagerService.this.getInstantAppPackageName(uid);
23775        }
23776
23777        @Override
23778        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23779            synchronized (mPackages) {
23780                return PackageManagerService.this.filterAppAccessLPr(
23781                        (PackageSetting) pkg.mExtras, callingUid, userId);
23782            }
23783        }
23784
23785        @Override
23786        public PackageParser.Package getPackage(String packageName) {
23787            synchronized (mPackages) {
23788                packageName = resolveInternalPackageNameLPr(
23789                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23790                return mPackages.get(packageName);
23791            }
23792        }
23793
23794        @Override
23795        public PackageList getPackageList(PackageListObserver observer) {
23796            synchronized (mPackages) {
23797                final int N = mPackages.size();
23798                final ArrayList<String> list = new ArrayList<>(N);
23799                for (int i = 0; i < N; i++) {
23800                    list.add(mPackages.keyAt(i));
23801                }
23802                final PackageList packageList = new PackageList(list, observer);
23803                if (observer != null) {
23804                    mPackageListObservers.add(packageList);
23805                }
23806                return packageList;
23807            }
23808        }
23809
23810        @Override
23811        public void removePackageListObserver(PackageListObserver observer) {
23812            synchronized (mPackages) {
23813                mPackageListObservers.remove(observer);
23814            }
23815        }
23816
23817        @Override
23818        public PackageParser.Package getDisabledPackage(String packageName) {
23819            synchronized (mPackages) {
23820                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23821                return (ps != null) ? ps.pkg : null;
23822            }
23823        }
23824
23825        @Override
23826        public String getKnownPackageName(int knownPackage, int userId) {
23827            switch(knownPackage) {
23828                case PackageManagerInternal.PACKAGE_BROWSER:
23829                    return getDefaultBrowserPackageName(userId);
23830                case PackageManagerInternal.PACKAGE_INSTALLER:
23831                    return mRequiredInstallerPackage;
23832                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23833                    return mSetupWizardPackage;
23834                case PackageManagerInternal.PACKAGE_SYSTEM:
23835                    return "android";
23836                case PackageManagerInternal.PACKAGE_VERIFIER:
23837                    return mRequiredVerifierPackage;
23838                case PackageManagerInternal.PACKAGE_SYSTEM_TEXT_CLASSIFIER:
23839                    return mSystemTextClassifierPackage;
23840            }
23841            return null;
23842        }
23843
23844        @Override
23845        public boolean isResolveActivityComponent(ComponentInfo component) {
23846            return mResolveActivity.packageName.equals(component.packageName)
23847                    && mResolveActivity.name.equals(component.name);
23848        }
23849
23850        @Override
23851        public void setLocationPackagesProvider(PackagesProvider provider) {
23852            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23853        }
23854
23855        @Override
23856        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23857            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23858        }
23859
23860        @Override
23861        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23862            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23863        }
23864
23865        @Override
23866        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23867            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23868        }
23869
23870        @Override
23871        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23872            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23873        }
23874
23875        @Override
23876        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23877            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23878        }
23879
23880        @Override
23881        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23882            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23883        }
23884
23885        @Override
23886        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23887            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23888        }
23889
23890        @Override
23891        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23892            synchronized (mPackages) {
23893                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23894            }
23895            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23896        }
23897
23898        @Override
23899        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23900            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23901                    packageName, userId);
23902        }
23903
23904        @Override
23905        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23906            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23907                    packageName, userId);
23908        }
23909
23910        @Override
23911        public void setKeepUninstalledPackages(final List<String> packageList) {
23912            Preconditions.checkNotNull(packageList);
23913            List<String> removedFromList = null;
23914            synchronized (mPackages) {
23915                if (mKeepUninstalledPackages != null) {
23916                    final int packagesCount = mKeepUninstalledPackages.size();
23917                    for (int i = 0; i < packagesCount; i++) {
23918                        String oldPackage = mKeepUninstalledPackages.get(i);
23919                        if (packageList != null && packageList.contains(oldPackage)) {
23920                            continue;
23921                        }
23922                        if (removedFromList == null) {
23923                            removedFromList = new ArrayList<>();
23924                        }
23925                        removedFromList.add(oldPackage);
23926                    }
23927                }
23928                mKeepUninstalledPackages = new ArrayList<>(packageList);
23929                if (removedFromList != null) {
23930                    final int removedCount = removedFromList.size();
23931                    for (int i = 0; i < removedCount; i++) {
23932                        deletePackageIfUnusedLPr(removedFromList.get(i));
23933                    }
23934                }
23935            }
23936        }
23937
23938        @Override
23939        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23940            synchronized (mPackages) {
23941                return mPermissionManager.isPermissionsReviewRequired(
23942                        mPackages.get(packageName), userId);
23943            }
23944        }
23945
23946        @Override
23947        public PackageInfo getPackageInfo(
23948                String packageName, int flags, int filterCallingUid, int userId) {
23949            return PackageManagerService.this
23950                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23951                            flags, filterCallingUid, userId);
23952        }
23953
23954        @Override
23955        public Bundle getSuspendedPackageLauncherExtras(String packageName, int userId) {
23956            synchronized (mPackages) {
23957                final PackageSetting ps = mSettings.mPackages.get(packageName);
23958                PersistableBundle launcherExtras = null;
23959                if (ps != null) {
23960                    launcherExtras = ps.readUserState(userId).suspendedLauncherExtras;
23961                }
23962                return (launcherExtras != null) ? new Bundle(launcherExtras.deepCopy()) : null;
23963            }
23964        }
23965
23966        @Override
23967        public boolean isPackageSuspended(String packageName, int userId) {
23968            synchronized (mPackages) {
23969                final PackageSetting ps = mSettings.mPackages.get(packageName);
23970                return (ps != null) ? ps.getSuspended(userId) : false;
23971            }
23972        }
23973
23974        @Override
23975        public String getSuspendingPackage(String suspendedPackage, int userId) {
23976            synchronized (mPackages) {
23977                final PackageSetting ps = mSettings.mPackages.get(suspendedPackage);
23978                return (ps != null) ? ps.readUserState(userId).suspendingPackage : null;
23979            }
23980        }
23981
23982        @Override
23983        public String getSuspendedDialogMessage(String suspendedPackage, int userId) {
23984            synchronized (mPackages) {
23985                final PackageSetting ps = mSettings.mPackages.get(suspendedPackage);
23986                return (ps != null) ? ps.readUserState(userId).dialogMessage : null;
23987            }
23988        }
23989
23990        @Override
23991        public int getPackageUid(String packageName, int flags, int userId) {
23992            return PackageManagerService.this
23993                    .getPackageUid(packageName, flags, userId);
23994        }
23995
23996        @Override
23997        public ApplicationInfo getApplicationInfo(
23998                String packageName, int flags, int filterCallingUid, int userId) {
23999            return PackageManagerService.this
24000                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24001        }
24002
24003        @Override
24004        public ActivityInfo getActivityInfo(
24005                ComponentName component, int flags, int filterCallingUid, int userId) {
24006            return PackageManagerService.this
24007                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24008        }
24009
24010        @Override
24011        public List<ResolveInfo> queryIntentActivities(
24012                Intent intent, int flags, int filterCallingUid, int userId) {
24013            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24014            return PackageManagerService.this
24015                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24016                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
24017        }
24018
24019        @Override
24020        public List<ResolveInfo> queryIntentServices(
24021                Intent intent, int flags, int callingUid, int userId) {
24022            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24023            return PackageManagerService.this
24024                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
24025                            false);
24026        }
24027
24028        @Override
24029        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24030                int userId) {
24031            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24032        }
24033
24034        @Override
24035        public ComponentName getDefaultHomeActivity(int userId) {
24036            return PackageManagerService.this.getDefaultHomeActivity(userId);
24037        }
24038
24039        @Override
24040        public void setDeviceAndProfileOwnerPackages(
24041                int deviceOwnerUserId, String deviceOwnerPackage,
24042                SparseArray<String> profileOwnerPackages) {
24043            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24044                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24045
24046            final ArraySet<Integer> usersWithPoOrDo = new ArraySet<>();
24047            if (deviceOwnerPackage != null) {
24048                usersWithPoOrDo.add(deviceOwnerUserId);
24049            }
24050            final int sz = profileOwnerPackages.size();
24051            for (int i = 0; i < sz; i++) {
24052                if (profileOwnerPackages.valueAt(i) != null) {
24053                    usersWithPoOrDo.add(profileOwnerPackages.keyAt(i));
24054                }
24055            }
24056            unsuspendForNonSystemSuspendingPackages(usersWithPoOrDo);
24057        }
24058
24059        @Override
24060        public boolean isPackageDataProtected(int userId, String packageName) {
24061            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24062        }
24063
24064        @Override
24065        public boolean isPackageStateProtected(String packageName, int userId) {
24066            return mProtectedPackages.isPackageStateProtected(userId, packageName);
24067        }
24068
24069        @Override
24070        public boolean isPackageEphemeral(int userId, String packageName) {
24071            synchronized (mPackages) {
24072                final PackageSetting ps = mSettings.mPackages.get(packageName);
24073                return ps != null ? ps.getInstantApp(userId) : false;
24074            }
24075        }
24076
24077        @Override
24078        public boolean wasPackageEverLaunched(String packageName, int userId) {
24079            synchronized (mPackages) {
24080                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24081            }
24082        }
24083
24084        @Override
24085        public void grantRuntimePermission(String packageName, String permName, int userId,
24086                boolean overridePolicy) {
24087            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
24088                    permName, packageName, overridePolicy, getCallingUid(), userId,
24089                    mPermissionCallback);
24090        }
24091
24092        @Override
24093        public void revokeRuntimePermission(String packageName, String permName, int userId,
24094                boolean overridePolicy) {
24095            mPermissionManager.revokeRuntimePermission(
24096                    permName, packageName, overridePolicy, getCallingUid(), userId,
24097                    mPermissionCallback);
24098        }
24099
24100        @Override
24101        public String getNameForUid(int uid) {
24102            return PackageManagerService.this.getNameForUid(uid);
24103        }
24104
24105        @Override
24106        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24107                Intent origIntent, String resolvedType, String callingPackage,
24108                Bundle verificationBundle, int userId) {
24109            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24110                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24111                    userId);
24112        }
24113
24114        @Override
24115        public void grantEphemeralAccess(int userId, Intent intent,
24116                int targetAppId, int ephemeralAppId) {
24117            synchronized (mPackages) {
24118                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24119                        targetAppId, ephemeralAppId);
24120            }
24121        }
24122
24123        @Override
24124        public boolean isInstantAppInstallerComponent(ComponentName component) {
24125            synchronized (mPackages) {
24126                return mInstantAppInstallerActivity != null
24127                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24128            }
24129        }
24130
24131        @Override
24132        public void pruneInstantApps() {
24133            mInstantAppRegistry.pruneInstantApps();
24134        }
24135
24136        @Override
24137        public String getSetupWizardPackageName() {
24138            return mSetupWizardPackage;
24139        }
24140
24141        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24142            if (policy != null) {
24143                mExternalSourcesPolicy = policy;
24144            }
24145        }
24146
24147        @Override
24148        public boolean isPackagePersistent(String packageName) {
24149            synchronized (mPackages) {
24150                PackageParser.Package pkg = mPackages.get(packageName);
24151                return pkg != null
24152                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24153                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24154                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24155                        : false;
24156            }
24157        }
24158
24159        @Override
24160        public boolean isLegacySystemApp(Package pkg) {
24161            synchronized (mPackages) {
24162                final PackageSetting ps = (PackageSetting) pkg.mExtras;
24163                return mPromoteSystemApps
24164                        && ps.isSystem()
24165                        && mExistingSystemPackages.contains(ps.name);
24166            }
24167        }
24168
24169        @Override
24170        public List<PackageInfo> getOverlayPackages(int userId) {
24171            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24172            synchronized (mPackages) {
24173                for (PackageParser.Package p : mPackages.values()) {
24174                    if (p.mOverlayTarget != null) {
24175                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24176                        if (pkg != null) {
24177                            overlayPackages.add(pkg);
24178                        }
24179                    }
24180                }
24181            }
24182            return overlayPackages;
24183        }
24184
24185        @Override
24186        public List<String> getTargetPackageNames(int userId) {
24187            List<String> targetPackages = new ArrayList<>();
24188            synchronized (mPackages) {
24189                for (PackageParser.Package p : mPackages.values()) {
24190                    if (p.mOverlayTarget == null) {
24191                        targetPackages.add(p.packageName);
24192                    }
24193                }
24194            }
24195            return targetPackages;
24196        }
24197
24198        @Override
24199        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24200                @Nullable List<String> overlayPackageNames) {
24201            synchronized (mPackages) {
24202                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24203                    Slog.e(TAG, "failed to find package " + targetPackageName);
24204                    return false;
24205                }
24206                ArrayList<String> overlayPaths = null;
24207                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24208                    final int N = overlayPackageNames.size();
24209                    overlayPaths = new ArrayList<>(N);
24210                    for (int i = 0; i < N; i++) {
24211                        final String packageName = overlayPackageNames.get(i);
24212                        final PackageParser.Package pkg = mPackages.get(packageName);
24213                        if (pkg == null) {
24214                            Slog.e(TAG, "failed to find package " + packageName);
24215                            return false;
24216                        }
24217                        overlayPaths.add(pkg.baseCodePath);
24218                    }
24219                }
24220
24221                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24222                ps.setOverlayPaths(overlayPaths, userId);
24223                return true;
24224            }
24225        }
24226
24227        @Override
24228        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24229                int flags, int userId, boolean resolveForStart, int filterCallingUid) {
24230            return resolveIntentInternal(
24231                    intent, resolvedType, flags, userId, resolveForStart, filterCallingUid);
24232        }
24233
24234        @Override
24235        public ResolveInfo resolveService(Intent intent, String resolvedType,
24236                int flags, int userId, int callingUid) {
24237            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24238        }
24239
24240        @Override
24241        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
24242            return PackageManagerService.this.resolveContentProviderInternal(
24243                    name, flags, userId);
24244        }
24245
24246        @Override
24247        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24248            synchronized (mPackages) {
24249                mIsolatedOwners.put(isolatedUid, ownerUid);
24250            }
24251        }
24252
24253        @Override
24254        public void removeIsolatedUid(int isolatedUid) {
24255            synchronized (mPackages) {
24256                mIsolatedOwners.delete(isolatedUid);
24257            }
24258        }
24259
24260        @Override
24261        public int getUidTargetSdkVersion(int uid) {
24262            synchronized (mPackages) {
24263                return getUidTargetSdkVersionLockedLPr(uid);
24264            }
24265        }
24266
24267        @Override
24268        public int getPackageTargetSdkVersion(String packageName) {
24269            synchronized (mPackages) {
24270                return getPackageTargetSdkVersionLockedLPr(packageName);
24271            }
24272        }
24273
24274        @Override
24275        public boolean canAccessInstantApps(int callingUid, int userId) {
24276            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24277        }
24278
24279        @Override
24280        public boolean canAccessComponent(int callingUid, ComponentName component, int userId) {
24281            synchronized (mPackages) {
24282                final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
24283                return !PackageManagerService.this.filterAppAccessLPr(
24284                        ps, callingUid, component, TYPE_UNKNOWN, userId);
24285            }
24286        }
24287
24288        @Override
24289        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
24290            synchronized (mPackages) {
24291                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
24292            }
24293        }
24294
24295        @Override
24296        public void notifyPackageUse(String packageName, int reason) {
24297            synchronized (mPackages) {
24298                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
24299            }
24300        }
24301    }
24302
24303    @Override
24304    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24305        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24306        synchronized (mPackages) {
24307            final long identity = Binder.clearCallingIdentity();
24308            try {
24309                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
24310                        packageNames, userId);
24311            } finally {
24312                Binder.restoreCallingIdentity(identity);
24313            }
24314        }
24315    }
24316
24317    @Override
24318    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24319        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24320        synchronized (mPackages) {
24321            final long identity = Binder.clearCallingIdentity();
24322            try {
24323                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
24324                        packageNames, userId);
24325            } finally {
24326                Binder.restoreCallingIdentity(identity);
24327            }
24328        }
24329    }
24330
24331    @Override
24332    public void grantDefaultPermissionsToEnabledTelephonyDataServices(
24333            String[] packageNames, int userId) {
24334        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledTelephonyDataServices");
24335        synchronized (mPackages) {
24336            Binder.withCleanCallingIdentity( () -> {
24337                mDefaultPermissionPolicy.
24338                        grantDefaultPermissionsToEnabledTelephonyDataServices(
24339                                packageNames, userId);
24340            });
24341        }
24342    }
24343
24344    @Override
24345    public void revokeDefaultPermissionsFromDisabledTelephonyDataServices(
24346            String[] packageNames, int userId) {
24347        enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromDisabledTelephonyDataServices");
24348        synchronized (mPackages) {
24349            Binder.withCleanCallingIdentity( () -> {
24350                mDefaultPermissionPolicy.
24351                        revokeDefaultPermissionsFromDisabledTelephonyDataServices(
24352                                packageNames, userId);
24353            });
24354        }
24355    }
24356
24357    @Override
24358    public void grantDefaultPermissionsToActiveLuiApp(String packageName, int userId) {
24359        enforceSystemOrPhoneCaller("grantDefaultPermissionsToActiveLuiApp");
24360        synchronized (mPackages) {
24361            final long identity = Binder.clearCallingIdentity();
24362            try {
24363                mDefaultPermissionPolicy.grantDefaultPermissionsToActiveLuiApp(
24364                        packageName, userId);
24365            } finally {
24366                Binder.restoreCallingIdentity(identity);
24367            }
24368        }
24369    }
24370
24371    @Override
24372    public void revokeDefaultPermissionsFromLuiApps(String[] packageNames, int userId) {
24373        enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromLuiApps");
24374        synchronized (mPackages) {
24375            final long identity = Binder.clearCallingIdentity();
24376            try {
24377                mDefaultPermissionPolicy.revokeDefaultPermissionsFromLuiApps(packageNames, userId);
24378            } finally {
24379                Binder.restoreCallingIdentity(identity);
24380            }
24381        }
24382    }
24383
24384    private static void enforceSystemOrPhoneCaller(String tag) {
24385        int callingUid = Binder.getCallingUid();
24386        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24387            throw new SecurityException(
24388                    "Cannot call " + tag + " from UID " + callingUid);
24389        }
24390    }
24391
24392    boolean isHistoricalPackageUsageAvailable() {
24393        return mPackageUsage.isHistoricalPackageUsageAvailable();
24394    }
24395
24396    /**
24397     * Return a <b>copy</b> of the collection of packages known to the package manager.
24398     * @return A copy of the values of mPackages.
24399     */
24400    Collection<PackageParser.Package> getPackages() {
24401        synchronized (mPackages) {
24402            return new ArrayList<>(mPackages.values());
24403        }
24404    }
24405
24406    /**
24407     * Logs process start information (including base APK hash) to the security log.
24408     * @hide
24409     */
24410    @Override
24411    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24412            String apkFile, int pid) {
24413        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24414            return;
24415        }
24416        if (!SecurityLog.isLoggingEnabled()) {
24417            return;
24418        }
24419        Bundle data = new Bundle();
24420        data.putLong("startTimestamp", System.currentTimeMillis());
24421        data.putString("processName", processName);
24422        data.putInt("uid", uid);
24423        data.putString("seinfo", seinfo);
24424        data.putString("apkFile", apkFile);
24425        data.putInt("pid", pid);
24426        Message msg = mProcessLoggingHandler.obtainMessage(
24427                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24428        msg.setData(data);
24429        mProcessLoggingHandler.sendMessage(msg);
24430    }
24431
24432    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24433        return mCompilerStats.getPackageStats(pkgName);
24434    }
24435
24436    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24437        return getOrCreateCompilerPackageStats(pkg.packageName);
24438    }
24439
24440    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24441        return mCompilerStats.getOrCreatePackageStats(pkgName);
24442    }
24443
24444    public void deleteCompilerPackageStats(String pkgName) {
24445        mCompilerStats.deletePackageStats(pkgName);
24446    }
24447
24448    @Override
24449    public int getInstallReason(String packageName, int userId) {
24450        final int callingUid = Binder.getCallingUid();
24451        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24452                true /* requireFullPermission */, false /* checkShell */,
24453                "get install reason");
24454        synchronized (mPackages) {
24455            final PackageSetting ps = mSettings.mPackages.get(packageName);
24456            if (filterAppAccessLPr(ps, callingUid, userId)) {
24457                return PackageManager.INSTALL_REASON_UNKNOWN;
24458            }
24459            if (ps != null) {
24460                return ps.getInstallReason(userId);
24461            }
24462        }
24463        return PackageManager.INSTALL_REASON_UNKNOWN;
24464    }
24465
24466    @Override
24467    public boolean canRequestPackageInstalls(String packageName, int userId) {
24468        return canRequestPackageInstallsInternal(packageName, 0, userId,
24469                true /* throwIfPermNotDeclared*/);
24470    }
24471
24472    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24473            boolean throwIfPermNotDeclared) {
24474        int callingUid = Binder.getCallingUid();
24475        int uid = getPackageUid(packageName, 0, userId);
24476        if (callingUid != uid && callingUid != Process.ROOT_UID
24477                && callingUid != Process.SYSTEM_UID) {
24478            throw new SecurityException(
24479                    "Caller uid " + callingUid + " does not own package " + packageName);
24480        }
24481        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24482        if (info == null) {
24483            return false;
24484        }
24485        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24486            return false;
24487        }
24488        if (isInstantApp(packageName, userId)) {
24489            return false;
24490        }
24491        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24492        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24493        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24494            if (throwIfPermNotDeclared) {
24495                throw new SecurityException("Need to declare " + appOpPermission
24496                        + " to call this api");
24497            } else {
24498                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24499                return false;
24500            }
24501        }
24502        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24503            return false;
24504        }
24505        if (mExternalSourcesPolicy != null) {
24506            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24507            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24508                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24509            }
24510        }
24511        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24512    }
24513
24514    @Override
24515    public ComponentName getInstantAppResolverSettingsComponent() {
24516        return mInstantAppResolverSettingsComponent;
24517    }
24518
24519    @Override
24520    public ComponentName getInstantAppInstallerComponent() {
24521        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24522            return null;
24523        }
24524        return mInstantAppInstallerActivity == null
24525                ? null : mInstantAppInstallerActivity.getComponentName();
24526    }
24527
24528    @Override
24529    public String getInstantAppAndroidId(String packageName, int userId) {
24530        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24531                "getInstantAppAndroidId");
24532        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
24533                true /* requireFullPermission */, false /* checkShell */,
24534                "getInstantAppAndroidId");
24535        // Make sure the target is an Instant App.
24536        if (!isInstantApp(packageName, userId)) {
24537            return null;
24538        }
24539        synchronized (mPackages) {
24540            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24541        }
24542    }
24543
24544    boolean canHaveOatDir(String packageName) {
24545        synchronized (mPackages) {
24546            PackageParser.Package p = mPackages.get(packageName);
24547            if (p == null) {
24548                return false;
24549            }
24550            return p.canHaveOatDir();
24551        }
24552    }
24553
24554    private String getOatDir(PackageParser.Package pkg) {
24555        if (!pkg.canHaveOatDir()) {
24556            return null;
24557        }
24558        File codePath = new File(pkg.codePath);
24559        if (codePath.isDirectory()) {
24560            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
24561        }
24562        return null;
24563    }
24564
24565    void deleteOatArtifactsOfPackage(String packageName) {
24566        final String[] instructionSets;
24567        final List<String> codePaths;
24568        final String oatDir;
24569        final PackageParser.Package pkg;
24570        synchronized (mPackages) {
24571            pkg = mPackages.get(packageName);
24572        }
24573        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24574        codePaths = pkg.getAllCodePaths();
24575        oatDir = getOatDir(pkg);
24576
24577        for (String codePath : codePaths) {
24578            for (String isa : instructionSets) {
24579                try {
24580                    mInstaller.deleteOdex(codePath, isa, oatDir);
24581                } catch (InstallerException e) {
24582                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24583                }
24584            }
24585        }
24586    }
24587
24588    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24589        Set<String> unusedPackages = new HashSet<>();
24590        long currentTimeInMillis = System.currentTimeMillis();
24591        synchronized (mPackages) {
24592            for (PackageParser.Package pkg : mPackages.values()) {
24593                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24594                if (ps == null) {
24595                    continue;
24596                }
24597                PackageDexUsage.PackageUseInfo packageUseInfo =
24598                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24599                if (PackageManagerServiceUtils
24600                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24601                                downgradeTimeThresholdMillis, packageUseInfo,
24602                                pkg.getLatestPackageUseTimeInMills(),
24603                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24604                    unusedPackages.add(pkg.packageName);
24605                }
24606            }
24607        }
24608        return unusedPackages;
24609    }
24610
24611    @Override
24612    public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
24613            int userId) {
24614        final int callingUid = Binder.getCallingUid();
24615        final int callingAppId = UserHandle.getAppId(callingUid);
24616
24617        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24618                true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
24619
24620        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24621                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24622            throw new SecurityException("Caller must have the "
24623                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24624        }
24625
24626        synchronized(mPackages) {
24627            mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
24628            scheduleWritePackageRestrictionsLocked(userId);
24629        }
24630    }
24631
24632    @Nullable
24633    @Override
24634    public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
24635        final int callingUid = Binder.getCallingUid();
24636        final int callingAppId = UserHandle.getAppId(callingUid);
24637
24638        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24639                true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
24640
24641        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24642                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24643            throw new SecurityException("Caller must have the "
24644                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24645        }
24646
24647        synchronized(mPackages) {
24648            return mSettings.getHarmfulAppWarningLPr(packageName, userId);
24649        }
24650    }
24651
24652    @Override
24653    public boolean isPackageStateProtected(@NonNull String packageName, @UserIdInt int userId) {
24654        final int callingUid = Binder.getCallingUid();
24655        final int callingAppId = UserHandle.getAppId(callingUid);
24656
24657        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24658                false /*requireFullPermission*/, true /*checkShell*/, "isPackageStateProtected");
24659
24660        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID
24661                && checkUidPermission(MANAGE_DEVICE_ADMINS, callingUid) != PERMISSION_GRANTED) {
24662            throw new SecurityException("Caller must have the "
24663                    + MANAGE_DEVICE_ADMINS + " permission.");
24664        }
24665
24666        return mProtectedPackages.isPackageStateProtected(userId, packageName);
24667    }
24668}
24669
24670interface PackageSender {
24671    /**
24672     * @param userIds User IDs where the action occurred on a full application
24673     * @param instantUserIds User IDs where the action occurred on an instant application
24674     */
24675    void sendPackageBroadcast(final String action, final String pkg,
24676        final Bundle extras, final int flags, final String targetPkg,
24677        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
24678    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24679        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
24680    void notifyPackageAdded(String packageName);
24681    void notifyPackageRemoved(String packageName);
24682}
24683