PackageManagerService.java revision 785d618b1a4c66d885cafec34ed1981daee6736d
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;
370
371/**
372 * Keep track of all those APKs everywhere.
373 * <p>
374 * Internally there are two important locks:
375 * <ul>
376 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
377 * and other related state. It is a fine-grained lock that should only be held
378 * momentarily, as it's one of the most contended locks in the system.
379 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
380 * operations typically involve heavy lifting of application data on disk. Since
381 * {@code installd} is single-threaded, and it's operations can often be slow,
382 * this lock should never be acquired while already holding {@link #mPackages}.
383 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
384 * holding {@link #mInstallLock}.
385 * </ul>
386 * Many internal methods rely on the caller to hold the appropriate locks, and
387 * this contract is expressed through method name suffixes:
388 * <ul>
389 * <li>fooLI(): the caller must hold {@link #mInstallLock}
390 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
391 * being modified must be frozen
392 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
393 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
394 * </ul>
395 * <p>
396 * Because this class is very central to the platform's security; please run all
397 * CTS and unit tests whenever making modifications:
398 *
399 * <pre>
400 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
401 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
402 * </pre>
403 */
404public class PackageManagerService extends IPackageManager.Stub
405        implements PackageSender {
406    static final String TAG = "PackageManager";
407    public static final boolean DEBUG_SETTINGS = false;
408    static final boolean DEBUG_PREFERRED = false;
409    static final boolean DEBUG_UPGRADE = false;
410    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
411    private static final boolean DEBUG_BACKUP = false;
412    public static final boolean DEBUG_INSTALL = false;
413    public static final boolean DEBUG_REMOVE = false;
414    private static final boolean DEBUG_BROADCASTS = false;
415    private static final boolean DEBUG_SHOW_INFO = false;
416    private static final boolean DEBUG_PACKAGE_INFO = false;
417    private static final boolean DEBUG_INTENT_MATCHING = false;
418    public static final boolean DEBUG_PACKAGE_SCANNING = false;
419    private static final boolean DEBUG_VERIFY = false;
420    private static final boolean DEBUG_FILTERS = false;
421    public static final boolean DEBUG_PERMISSIONS = false;
422    private static final boolean DEBUG_SHARED_LIBRARIES = false;
423    public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
424
425    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
426    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
427    // user, but by default initialize to this.
428    public static final boolean DEBUG_DEXOPT = false;
429
430    private static final boolean DEBUG_ABI_SELECTION = false;
431    private static final boolean DEBUG_INSTANT = Build.IS_DEBUGGABLE;
432    private static final boolean DEBUG_TRIAGED_MISSING = false;
433    private static final boolean DEBUG_APP_DATA = false;
434
435    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
436    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
437
438    private static final boolean HIDE_EPHEMERAL_APIS = false;
439
440    private static final boolean ENABLE_FREE_CACHE_V2 =
441            SystemProperties.getBoolean("fw.free_cache_v2", true);
442
443    private static final int RADIO_UID = Process.PHONE_UID;
444    private static final int LOG_UID = Process.LOG_UID;
445    private static final int NFC_UID = Process.NFC_UID;
446    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
447    private static final int SHELL_UID = Process.SHELL_UID;
448    private static final int SE_UID = Process.SE_UID;
449
450    // Suffix used during package installation when copying/moving
451    // package apks to install directory.
452    private static final String INSTALL_PACKAGE_SUFFIX = "-";
453
454    static final int SCAN_NO_DEX = 1<<0;
455    static final int SCAN_UPDATE_SIGNATURE = 1<<1;
456    static final int SCAN_NEW_INSTALL = 1<<2;
457    static final int SCAN_UPDATE_TIME = 1<<3;
458    static final int SCAN_BOOTING = 1<<4;
459    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6;
460    static final int SCAN_REQUIRE_KNOWN = 1<<7;
461    static final int SCAN_MOVE = 1<<8;
462    static final int SCAN_INITIAL = 1<<9;
463    static final int SCAN_CHECK_ONLY = 1<<10;
464    static final int SCAN_DONT_KILL_APP = 1<<11;
465    static final int SCAN_IGNORE_FROZEN = 1<<12;
466    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13;
467    static final int SCAN_AS_INSTANT_APP = 1<<14;
468    static final int SCAN_AS_FULL_APP = 1<<15;
469    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16;
470    static final int SCAN_AS_SYSTEM = 1<<17;
471    static final int SCAN_AS_PRIVILEGED = 1<<18;
472    static final int SCAN_AS_OEM = 1<<19;
473    static final int SCAN_AS_VENDOR = 1<<20;
474    static final int SCAN_AS_PRODUCT = 1<<21;
475
476    @IntDef(flag = true, prefix = { "SCAN_" }, value = {
477            SCAN_NO_DEX,
478            SCAN_UPDATE_SIGNATURE,
479            SCAN_NEW_INSTALL,
480            SCAN_UPDATE_TIME,
481            SCAN_BOOTING,
482            SCAN_DELETE_DATA_ON_FAILURES,
483            SCAN_REQUIRE_KNOWN,
484            SCAN_MOVE,
485            SCAN_INITIAL,
486            SCAN_CHECK_ONLY,
487            SCAN_DONT_KILL_APP,
488            SCAN_IGNORE_FROZEN,
489            SCAN_FIRST_BOOT_OR_UPGRADE,
490            SCAN_AS_INSTANT_APP,
491            SCAN_AS_FULL_APP,
492            SCAN_AS_VIRTUAL_PRELOAD,
493    })
494    @Retention(RetentionPolicy.SOURCE)
495    public @interface ScanFlags {}
496
497    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
498    /** Extension of the compressed packages */
499    public final static String COMPRESSED_EXTENSION = ".gz";
500    /** Suffix of stub packages on the system partition */
501    public final static String STUB_SUFFIX = "-Stub";
502
503    private static final int[] EMPTY_INT_ARRAY = new int[0];
504
505    private static final int TYPE_UNKNOWN = 0;
506    private static final int TYPE_ACTIVITY = 1;
507    private static final int TYPE_RECEIVER = 2;
508    private static final int TYPE_SERVICE = 3;
509    private static final int TYPE_PROVIDER = 4;
510    @IntDef(prefix = { "TYPE_" }, value = {
511            TYPE_UNKNOWN,
512            TYPE_ACTIVITY,
513            TYPE_RECEIVER,
514            TYPE_SERVICE,
515            TYPE_PROVIDER,
516    })
517    @Retention(RetentionPolicy.SOURCE)
518    public @interface ComponentType {}
519
520    /**
521     * Timeout (in milliseconds) after which the watchdog should declare that
522     * our handler thread is wedged.  The usual default for such things is one
523     * minute but we sometimes do very lengthy I/O operations on this thread,
524     * such as installing multi-gigabyte applications, so ours needs to be longer.
525     */
526    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
527
528    /**
529     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
530     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
531     * settings entry if available, otherwise we use the hardcoded default.  If it's been
532     * more than this long since the last fstrim, we force one during the boot sequence.
533     *
534     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
535     * one gets run at the next available charging+idle time.  This final mandatory
536     * no-fstrim check kicks in only of the other scheduling criteria is never met.
537     */
538    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
539
540    /**
541     * Whether verification is enabled by default.
542     */
543    private static final boolean DEFAULT_VERIFY_ENABLE = true;
544
545    /**
546     * The default maximum time to wait for the verification agent to return in
547     * milliseconds.
548     */
549    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
550
551    /**
552     * The default response for package verification timeout.
553     *
554     * This can be either PackageManager.VERIFICATION_ALLOW or
555     * PackageManager.VERIFICATION_REJECT.
556     */
557    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
558
559    public static final String PLATFORM_PACKAGE_NAME = "android";
560
561    public static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
562
563    public static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
564            DEFAULT_CONTAINER_PACKAGE,
565            "com.android.defcontainer.DefaultContainerService");
566
567    private static final String KILL_APP_REASON_GIDS_CHANGED =
568            "permission grant or revoke changed gids";
569
570    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
571            "permissions revoked";
572
573    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
574
575    private static final String PACKAGE_SCHEME = "package";
576
577    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
578
579    private static final String PRODUCT_OVERLAY_DIR = "/product/overlay";
580
581    /** Canonical intent used to identify what counts as a "web browser" app */
582    private static final Intent sBrowserIntent;
583    static {
584        sBrowserIntent = new Intent();
585        sBrowserIntent.setAction(Intent.ACTION_VIEW);
586        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
587        sBrowserIntent.setData(Uri.parse("http:"));
588        sBrowserIntent.addFlags(Intent.FLAG_IGNORE_EPHEMERAL);
589    }
590
591    /**
592     * The set of all protected actions [i.e. those actions for which a high priority
593     * intent filter is disallowed].
594     */
595    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
596    static {
597        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
598        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
599        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
600        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
601    }
602
603    // Compilation reasons.
604    public static final int REASON_UNKNOWN = -1;
605    public static final int REASON_FIRST_BOOT = 0;
606    public static final int REASON_BOOT = 1;
607    public static final int REASON_INSTALL = 2;
608    public static final int REASON_BACKGROUND_DEXOPT = 3;
609    public static final int REASON_AB_OTA = 4;
610    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
611    public static final int REASON_SHARED = 6;
612
613    public static final int REASON_LAST = REASON_SHARED;
614
615    /**
616     * Version number for the package parser cache. Increment this whenever the format or
617     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
618     */
619    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
620
621    /**
622     * Whether the package parser cache is enabled.
623     */
624    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
625
626    /**
627     * Permissions required in order to receive instant application lifecycle broadcasts.
628     */
629    private static final String[] INSTANT_APP_BROADCAST_PERMISSION =
630            new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS };
631
632    final ServiceThread mHandlerThread;
633
634    final PackageHandler mHandler;
635
636    private final ProcessLoggingHandler mProcessLoggingHandler;
637
638    /**
639     * Messages for {@link #mHandler} that need to wait for system ready before
640     * being dispatched.
641     */
642    private ArrayList<Message> mPostSystemReadyMessages;
643
644    final int mSdkVersion = Build.VERSION.SDK_INT;
645
646    final Context mContext;
647    final boolean mFactoryTest;
648    final boolean mOnlyCore;
649    final DisplayMetrics mMetrics;
650    final int mDefParseFlags;
651    final String[] mSeparateProcesses;
652    final boolean mIsUpgrade;
653    final boolean mIsPreNUpgrade;
654    final boolean mIsPreNMR1Upgrade;
655
656    // Have we told the Activity Manager to whitelist the default container service by uid yet?
657    @GuardedBy("mPackages")
658    boolean mDefaultContainerWhitelisted = false;
659
660    @GuardedBy("mPackages")
661    private boolean mDexOptDialogShown;
662
663    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
664    // LOCK HELD.  Can be called with mInstallLock held.
665    @GuardedBy("mInstallLock")
666    final Installer mInstaller;
667
668    /** Directory where installed applications are stored */
669    private static final File sAppInstallDir =
670            new File(Environment.getDataDirectory(), "app");
671    /** Directory where installed application's 32-bit native libraries are copied. */
672    private static final File sAppLib32InstallDir =
673            new File(Environment.getDataDirectory(), "app-lib");
674    /** Directory where code and non-resource assets of forward-locked applications are stored */
675    private static final File sDrmAppPrivateInstallDir =
676            new File(Environment.getDataDirectory(), "app-private");
677
678    // ----------------------------------------------------------------
679
680    // Lock for state used when installing and doing other long running
681    // operations.  Methods that must be called with this lock held have
682    // the suffix "LI".
683    final Object mInstallLock = new Object();
684
685    // ----------------------------------------------------------------
686
687    // Keys are String (package name), values are Package.  This also serves
688    // as the lock for the global state.  Methods that must be called with
689    // this lock held have the prefix "LP".
690    @GuardedBy("mPackages")
691    final ArrayMap<String, PackageParser.Package> mPackages =
692            new ArrayMap<String, PackageParser.Package>();
693
694    final ArrayMap<String, Set<String>> mKnownCodebase =
695            new ArrayMap<String, Set<String>>();
696
697    // Keys are isolated uids and values are the uid of the application
698    // that created the isolated proccess.
699    @GuardedBy("mPackages")
700    final SparseIntArray mIsolatedOwners = new SparseIntArray();
701
702    /**
703     * Tracks new system packages [received in an OTA] that we expect to
704     * find updated user-installed versions. Keys are package name, values
705     * are package location.
706     */
707    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
708    /**
709     * Tracks high priority intent filters for protected actions. During boot, certain
710     * filter actions are protected and should never be allowed to have a high priority
711     * intent filter for them. However, there is one, and only one exception -- the
712     * setup wizard. It must be able to define a high priority intent filter for these
713     * actions to ensure there are no escapes from the wizard. We need to delay processing
714     * of these during boot as we need to look at all of the system packages in order
715     * to know which component is the setup wizard.
716     */
717    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
718    /**
719     * Whether or not processing protected filters should be deferred.
720     */
721    private boolean mDeferProtectedFilters = true;
722
723    /**
724     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
725     */
726    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
727    /**
728     * Whether or not system app permissions should be promoted from install to runtime.
729     */
730    boolean mPromoteSystemApps;
731
732    @GuardedBy("mPackages")
733    final Settings mSettings;
734
735    /**
736     * Set of package names that are currently "frozen", which means active
737     * surgery is being done on the code/data for that package. The platform
738     * will refuse to launch frozen packages to avoid race conditions.
739     *
740     * @see PackageFreezer
741     */
742    @GuardedBy("mPackages")
743    final ArraySet<String> mFrozenPackages = new ArraySet<>();
744
745    final ProtectedPackages mProtectedPackages;
746
747    @GuardedBy("mLoadedVolumes")
748    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
749
750    boolean mFirstBoot;
751
752    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
753
754    @GuardedBy("mAvailableFeatures")
755    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
756
757    private final InstantAppRegistry mInstantAppRegistry;
758
759    @GuardedBy("mPackages")
760    int mChangedPackagesSequenceNumber;
761    /**
762     * List of changed [installed, removed or updated] packages.
763     * mapping from user id -> sequence number -> package name
764     */
765    @GuardedBy("mPackages")
766    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
767    /**
768     * The sequence number of the last change to a package.
769     * mapping from user id -> package name -> sequence number
770     */
771    @GuardedBy("mPackages")
772    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
773
774    @GuardedBy("mPackages")
775    final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>();
776
777    class PackageParserCallback implements PackageParser.Callback {
778        @Override public final boolean hasFeature(String feature) {
779            return PackageManagerService.this.hasSystemFeature(feature, 0);
780        }
781
782        final List<PackageParser.Package> getStaticOverlayPackages(
783                Collection<PackageParser.Package> allPackages, String targetPackageName) {
784            if ("android".equals(targetPackageName)) {
785                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
786                // native AssetManager.
787                return null;
788            }
789
790            List<PackageParser.Package> overlayPackages = null;
791            for (PackageParser.Package p : allPackages) {
792                if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) {
793                    if (overlayPackages == null) {
794                        overlayPackages = new ArrayList<PackageParser.Package>();
795                    }
796                    overlayPackages.add(p);
797                }
798            }
799            if (overlayPackages != null) {
800                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
801                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
802                        return p1.mOverlayPriority - p2.mOverlayPriority;
803                    }
804                };
805                Collections.sort(overlayPackages, cmp);
806            }
807            return overlayPackages;
808        }
809
810        final String[] getStaticOverlayPaths(List<PackageParser.Package> overlayPackages,
811                String targetPath) {
812            if (overlayPackages == null || overlayPackages.isEmpty()) {
813                return null;
814            }
815            List<String> overlayPathList = null;
816            for (PackageParser.Package overlayPackage : overlayPackages) {
817                if (targetPath == null) {
818                    if (overlayPathList == null) {
819                        overlayPathList = new ArrayList<String>();
820                    }
821                    overlayPathList.add(overlayPackage.baseCodePath);
822                    continue;
823                }
824
825                try {
826                    // Creates idmaps for system to parse correctly the Android manifest of the
827                    // target package.
828                    //
829                    // OverlayManagerService will update each of them with a correct gid from its
830                    // target package app id.
831                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
832                            UserHandle.getSharedAppGid(
833                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
834                    if (overlayPathList == null) {
835                        overlayPathList = new ArrayList<String>();
836                    }
837                    overlayPathList.add(overlayPackage.baseCodePath);
838                } catch (InstallerException e) {
839                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
840                            overlayPackage.baseCodePath);
841                }
842            }
843            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
844        }
845
846        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
847            List<PackageParser.Package> overlayPackages;
848            synchronized (mInstallLock) {
849                synchronized (mPackages) {
850                    overlayPackages = getStaticOverlayPackages(
851                            mPackages.values(), targetPackageName);
852                }
853                // It is safe to keep overlayPackages without holding mPackages because static overlay
854                // packages can't be uninstalled or disabled.
855                return getStaticOverlayPaths(overlayPackages, targetPath);
856            }
857        }
858
859        @Override public final String[] getOverlayApks(String targetPackageName) {
860            return getStaticOverlayPaths(targetPackageName, null);
861        }
862
863        @Override public final String[] getOverlayPaths(String targetPackageName,
864                String targetPath) {
865            return getStaticOverlayPaths(targetPackageName, targetPath);
866        }
867    }
868
869    class ParallelPackageParserCallback extends PackageParserCallback {
870        List<PackageParser.Package> mOverlayPackages = null;
871
872        void findStaticOverlayPackages() {
873            synchronized (mPackages) {
874                for (PackageParser.Package p : mPackages.values()) {
875                    if (p.mOverlayIsStatic) {
876                        if (mOverlayPackages == null) {
877                            mOverlayPackages = new ArrayList<PackageParser.Package>();
878                        }
879                        mOverlayPackages.add(p);
880                    }
881                }
882            }
883        }
884
885        @Override
886        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
887            // We can trust mOverlayPackages without holding mPackages because package uninstall
888            // can't happen while running parallel parsing.
889            // And we can call mInstaller inside getStaticOverlayPaths without holding mInstallLock
890            // because mInstallLock is held before running parallel parsing.
891            // Moreover holding mPackages or mInstallLock on each parsing thread causes dead-lock.
892            return mOverlayPackages == null ? null :
893                    getStaticOverlayPaths(
894                            getStaticOverlayPackages(mOverlayPackages, targetPackageName),
895                            targetPath);
896        }
897    }
898
899    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
900    final ParallelPackageParserCallback mParallelPackageParserCallback =
901            new ParallelPackageParserCallback();
902
903    public static final class SharedLibraryEntry {
904        public final @Nullable String path;
905        public final @Nullable String apk;
906        public final @NonNull SharedLibraryInfo info;
907
908        SharedLibraryEntry(String _path, String _apk, String name, long version, int type,
909                String declaringPackageName, long declaringPackageVersionCode) {
910            path = _path;
911            apk = _apk;
912            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
913                    declaringPackageName, declaringPackageVersionCode), null);
914        }
915    }
916
917    // Currently known shared libraries.
918    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
919    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
920            new ArrayMap<>();
921
922    // All available activities, for your resolving pleasure.
923    final ActivityIntentResolver mActivities =
924            new ActivityIntentResolver();
925
926    // All available receivers, for your resolving pleasure.
927    final ActivityIntentResolver mReceivers =
928            new ActivityIntentResolver();
929
930    // All available services, for your resolving pleasure.
931    final ServiceIntentResolver mServices = new ServiceIntentResolver();
932
933    // All available providers, for your resolving pleasure.
934    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
935
936    // Mapping from provider base names (first directory in content URI codePath)
937    // to the provider information.
938    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
939            new ArrayMap<String, PackageParser.Provider>();
940
941    // Mapping from instrumentation class names to info about them.
942    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
943            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
944
945    // Packages whose data we have transfered into another package, thus
946    // should no longer exist.
947    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
948
949    // Broadcast actions that are only available to the system.
950    @GuardedBy("mProtectedBroadcasts")
951    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
952
953    /** List of packages waiting for verification. */
954    final SparseArray<PackageVerificationState> mPendingVerification
955            = new SparseArray<PackageVerificationState>();
956
957    final PackageInstallerService mInstallerService;
958
959    final ArtManagerService mArtManagerService;
960
961    private final PackageDexOptimizer mPackageDexOptimizer;
962    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
963    // is used by other apps).
964    private final DexManager mDexManager;
965
966    private AtomicInteger mNextMoveId = new AtomicInteger();
967    private final MoveCallbacks mMoveCallbacks;
968
969    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
970
971    // Cache of users who need badging.
972    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
973
974    /** Token for keys in mPendingVerification. */
975    private int mPendingVerificationToken = 0;
976
977    volatile boolean mSystemReady;
978    volatile boolean mSafeMode;
979    volatile boolean mHasSystemUidErrors;
980    private volatile boolean mWebInstantAppsDisabled;
981
982    ApplicationInfo mAndroidApplication;
983    final ActivityInfo mResolveActivity = new ActivityInfo();
984    final ResolveInfo mResolveInfo = new ResolveInfo();
985    ComponentName mResolveComponentName;
986    PackageParser.Package mPlatformPackage;
987    ComponentName mCustomResolverComponentName;
988
989    boolean mResolverReplaced = false;
990
991    private final @Nullable ComponentName mIntentFilterVerifierComponent;
992    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
993
994    private int mIntentFilterVerificationToken = 0;
995
996    /** The service connection to the ephemeral resolver */
997    final InstantAppResolverConnection mInstantAppResolverConnection;
998    /** Component used to show resolver settings for Instant Apps */
999    final ComponentName mInstantAppResolverSettingsComponent;
1000
1001    /** Activity used to install instant applications */
1002    ActivityInfo mInstantAppInstallerActivity;
1003    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
1004
1005    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1006            = new SparseArray<IntentFilterVerificationState>();
1007
1008    // TODO remove this and go through mPermissonManager directly
1009    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1010    private final PermissionManagerInternal mPermissionManager;
1011
1012    // List of packages names to keep cached, even if they are uninstalled for all users
1013    private List<String> mKeepUninstalledPackages;
1014
1015    private UserManagerInternal mUserManagerInternal;
1016    private ActivityManagerInternal mActivityManagerInternal;
1017
1018    private DeviceIdleController.LocalService mDeviceIdleController;
1019
1020    private File mCacheDir;
1021
1022    private Future<?> mPrepareAppDataFuture;
1023
1024    private static class IFVerificationParams {
1025        PackageParser.Package pkg;
1026        boolean replacing;
1027        int userId;
1028        int verifierUid;
1029
1030        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1031                int _userId, int _verifierUid) {
1032            pkg = _pkg;
1033            replacing = _replacing;
1034            userId = _userId;
1035            replacing = _replacing;
1036            verifierUid = _verifierUid;
1037        }
1038    }
1039
1040    private interface IntentFilterVerifier<T extends IntentFilter> {
1041        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1042                                               T filter, String packageName);
1043        void startVerifications(int userId);
1044        void receiveVerificationResponse(int verificationId);
1045    }
1046
1047    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1048        private Context mContext;
1049        private ComponentName mIntentFilterVerifierComponent;
1050        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1051
1052        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1053            mContext = context;
1054            mIntentFilterVerifierComponent = verifierComponent;
1055        }
1056
1057        private String getDefaultScheme() {
1058            return IntentFilter.SCHEME_HTTPS;
1059        }
1060
1061        @Override
1062        public void startVerifications(int userId) {
1063            // Launch verifications requests
1064            int count = mCurrentIntentFilterVerifications.size();
1065            for (int n=0; n<count; n++) {
1066                int verificationId = mCurrentIntentFilterVerifications.get(n);
1067                final IntentFilterVerificationState ivs =
1068                        mIntentFilterVerificationStates.get(verificationId);
1069
1070                String packageName = ivs.getPackageName();
1071
1072                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1073                final int filterCount = filters.size();
1074                ArraySet<String> domainsSet = new ArraySet<>();
1075                for (int m=0; m<filterCount; m++) {
1076                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1077                    domainsSet.addAll(filter.getHostsList());
1078                }
1079                synchronized (mPackages) {
1080                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1081                            packageName, domainsSet) != null) {
1082                        scheduleWriteSettingsLocked();
1083                    }
1084                }
1085                sendVerificationRequest(verificationId, ivs);
1086            }
1087            mCurrentIntentFilterVerifications.clear();
1088        }
1089
1090        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1091            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1092            verificationIntent.putExtra(
1093                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1094                    verificationId);
1095            verificationIntent.putExtra(
1096                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1097                    getDefaultScheme());
1098            verificationIntent.putExtra(
1099                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1100                    ivs.getHostsString());
1101            verificationIntent.putExtra(
1102                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1103                    ivs.getPackageName());
1104            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1105            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1106
1107            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1108            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1109                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1110                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1111
1112            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1113            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1114                    "Sending IntentFilter verification broadcast");
1115        }
1116
1117        public void receiveVerificationResponse(int verificationId) {
1118            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1119
1120            final boolean verified = ivs.isVerified();
1121
1122            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1123            final int count = filters.size();
1124            if (DEBUG_DOMAIN_VERIFICATION) {
1125                Slog.i(TAG, "Received verification response " + verificationId
1126                        + " for " + count + " filters, verified=" + verified);
1127            }
1128            for (int n=0; n<count; n++) {
1129                PackageParser.ActivityIntentInfo filter = filters.get(n);
1130                filter.setVerified(verified);
1131
1132                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1133                        + " verified with result:" + verified + " and hosts:"
1134                        + ivs.getHostsString());
1135            }
1136
1137            mIntentFilterVerificationStates.remove(verificationId);
1138
1139            final String packageName = ivs.getPackageName();
1140            IntentFilterVerificationInfo ivi = null;
1141
1142            synchronized (mPackages) {
1143                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1144            }
1145            if (ivi == null) {
1146                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1147                        + verificationId + " packageName:" + packageName);
1148                return;
1149            }
1150            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1151                    "Updating IntentFilterVerificationInfo for package " + packageName
1152                            +" verificationId:" + verificationId);
1153
1154            synchronized (mPackages) {
1155                if (verified) {
1156                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1157                } else {
1158                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1159                }
1160                scheduleWriteSettingsLocked();
1161
1162                final int userId = ivs.getUserId();
1163                if (userId != UserHandle.USER_ALL) {
1164                    final int userStatus =
1165                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1166
1167                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1168                    boolean needUpdate = false;
1169
1170                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1171                    // already been set by the User thru the Disambiguation dialog
1172                    switch (userStatus) {
1173                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1174                            if (verified) {
1175                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1176                            } else {
1177                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1178                            }
1179                            needUpdate = true;
1180                            break;
1181
1182                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1183                            if (verified) {
1184                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1185                                needUpdate = true;
1186                            }
1187                            break;
1188
1189                        default:
1190                            // Nothing to do
1191                    }
1192
1193                    if (needUpdate) {
1194                        mSettings.updateIntentFilterVerificationStatusLPw(
1195                                packageName, updatedStatus, userId);
1196                        scheduleWritePackageRestrictionsLocked(userId);
1197                    }
1198                }
1199            }
1200        }
1201
1202        @Override
1203        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1204                    ActivityIntentInfo filter, String packageName) {
1205            if (!hasValidDomains(filter)) {
1206                return false;
1207            }
1208            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1209            if (ivs == null) {
1210                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1211                        packageName);
1212            }
1213            if (DEBUG_DOMAIN_VERIFICATION) {
1214                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1215            }
1216            ivs.addFilter(filter);
1217            return true;
1218        }
1219
1220        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1221                int userId, int verificationId, String packageName) {
1222            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1223                    verifierUid, userId, packageName);
1224            ivs.setPendingState();
1225            synchronized (mPackages) {
1226                mIntentFilterVerificationStates.append(verificationId, ivs);
1227                mCurrentIntentFilterVerifications.add(verificationId);
1228            }
1229            return ivs;
1230        }
1231    }
1232
1233    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1234        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1235                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1236                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1237    }
1238
1239    // Set of pending broadcasts for aggregating enable/disable of components.
1240    static class PendingPackageBroadcasts {
1241        // for each user id, a map of <package name -> components within that package>
1242        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1243
1244        public PendingPackageBroadcasts() {
1245            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1246        }
1247
1248        public ArrayList<String> get(int userId, String packageName) {
1249            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1250            return packages.get(packageName);
1251        }
1252
1253        public void put(int userId, String packageName, ArrayList<String> components) {
1254            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1255            packages.put(packageName, components);
1256        }
1257
1258        public void remove(int userId, String packageName) {
1259            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1260            if (packages != null) {
1261                packages.remove(packageName);
1262            }
1263        }
1264
1265        public void remove(int userId) {
1266            mUidMap.remove(userId);
1267        }
1268
1269        public int userIdCount() {
1270            return mUidMap.size();
1271        }
1272
1273        public int userIdAt(int n) {
1274            return mUidMap.keyAt(n);
1275        }
1276
1277        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1278            return mUidMap.get(userId);
1279        }
1280
1281        public int size() {
1282            // total number of pending broadcast entries across all userIds
1283            int num = 0;
1284            for (int i = 0; i< mUidMap.size(); i++) {
1285                num += mUidMap.valueAt(i).size();
1286            }
1287            return num;
1288        }
1289
1290        public void clear() {
1291            mUidMap.clear();
1292        }
1293
1294        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1295            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1296            if (map == null) {
1297                map = new ArrayMap<String, ArrayList<String>>();
1298                mUidMap.put(userId, map);
1299            }
1300            return map;
1301        }
1302    }
1303    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1304
1305    // Service Connection to remote media container service to copy
1306    // package uri's from external media onto secure containers
1307    // or internal storage.
1308    private IMediaContainerService mContainerService = null;
1309
1310    static final int SEND_PENDING_BROADCAST = 1;
1311    static final int MCS_BOUND = 3;
1312    static final int END_COPY = 4;
1313    static final int INIT_COPY = 5;
1314    static final int MCS_UNBIND = 6;
1315    static final int START_CLEANING_PACKAGE = 7;
1316    static final int FIND_INSTALL_LOC = 8;
1317    static final int POST_INSTALL = 9;
1318    static final int MCS_RECONNECT = 10;
1319    static final int MCS_GIVE_UP = 11;
1320    static final int WRITE_SETTINGS = 13;
1321    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1322    static final int PACKAGE_VERIFIED = 15;
1323    static final int CHECK_PENDING_VERIFICATION = 16;
1324    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1325    static final int INTENT_FILTER_VERIFIED = 18;
1326    static final int WRITE_PACKAGE_LIST = 19;
1327    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1328    static final int DEF_CONTAINER_BIND = 21;
1329
1330    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1331
1332    // Delay time in millisecs
1333    static final int BROADCAST_DELAY = 10 * 1000;
1334
1335    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1336            2 * 60 * 60 * 1000L; /* two hours */
1337
1338    static UserManagerService sUserManager;
1339
1340    // Stores a list of users whose package restrictions file needs to be updated
1341    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1342
1343    final private DefaultContainerConnection mDefContainerConn =
1344            new DefaultContainerConnection();
1345    class DefaultContainerConnection implements ServiceConnection {
1346        public void onServiceConnected(ComponentName name, IBinder service) {
1347            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1348            final IMediaContainerService imcs = IMediaContainerService.Stub
1349                    .asInterface(Binder.allowBlocking(service));
1350            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1351        }
1352
1353        public void onServiceDisconnected(ComponentName name) {
1354            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1355        }
1356    }
1357
1358    // Recordkeeping of restore-after-install operations that are currently in flight
1359    // between the Package Manager and the Backup Manager
1360    static class PostInstallData {
1361        public InstallArgs args;
1362        public PackageInstalledInfo res;
1363
1364        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1365            args = _a;
1366            res = _r;
1367        }
1368    }
1369
1370    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1371    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1372
1373    // XML tags for backup/restore of various bits of state
1374    private static final String TAG_PREFERRED_BACKUP = "pa";
1375    private static final String TAG_DEFAULT_APPS = "da";
1376    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1377
1378    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1379    private static final String TAG_ALL_GRANTS = "rt-grants";
1380    private static final String TAG_GRANT = "grant";
1381    private static final String ATTR_PACKAGE_NAME = "pkg";
1382
1383    private static final String TAG_PERMISSION = "perm";
1384    private static final String ATTR_PERMISSION_NAME = "name";
1385    private static final String ATTR_IS_GRANTED = "g";
1386    private static final String ATTR_USER_SET = "set";
1387    private static final String ATTR_USER_FIXED = "fixed";
1388    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1389
1390    // System/policy permission grants are not backed up
1391    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1392            FLAG_PERMISSION_POLICY_FIXED
1393            | FLAG_PERMISSION_SYSTEM_FIXED
1394            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1395
1396    // And we back up these user-adjusted states
1397    private static final int USER_RUNTIME_GRANT_MASK =
1398            FLAG_PERMISSION_USER_SET
1399            | FLAG_PERMISSION_USER_FIXED
1400            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1401
1402    final @Nullable String mRequiredVerifierPackage;
1403    final @NonNull String mRequiredInstallerPackage;
1404    final @NonNull String mRequiredUninstallerPackage;
1405    final @Nullable String mSetupWizardPackage;
1406    final @Nullable String mStorageManagerPackage;
1407    final @Nullable String mSystemTextClassifierPackage;
1408    final @NonNull String mServicesSystemSharedLibraryPackageName;
1409    final @NonNull String mSharedSystemSharedLibraryPackageName;
1410
1411    private final PackageUsage mPackageUsage = new PackageUsage();
1412    private final CompilerStats mCompilerStats = new CompilerStats();
1413
1414    class PackageHandler extends Handler {
1415        private boolean mBound = false;
1416        final ArrayList<HandlerParams> mPendingInstalls =
1417            new ArrayList<HandlerParams>();
1418
1419        private boolean connectToService() {
1420            if (DEBUG_INSTALL) Log.i(TAG, "Trying to bind to DefaultContainerService");
1421            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1422            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1423            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1424                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1425                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1426                mBound = true;
1427                return true;
1428            }
1429            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1430            return false;
1431        }
1432
1433        private void disconnectService() {
1434            mContainerService = null;
1435            mBound = false;
1436            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1437            mContext.unbindService(mDefContainerConn);
1438            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1439        }
1440
1441        PackageHandler(Looper looper) {
1442            super(looper);
1443        }
1444
1445        public void handleMessage(Message msg) {
1446            try {
1447                doHandleMessage(msg);
1448            } finally {
1449                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1450            }
1451        }
1452
1453        void doHandleMessage(Message msg) {
1454            switch (msg.what) {
1455                case DEF_CONTAINER_BIND:
1456                    if (!mBound) {
1457                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "earlyBindingMCS",
1458                                System.identityHashCode(mHandler));
1459                        if (!connectToService()) {
1460                            Slog.e(TAG, "Failed to bind to media container service");
1461                        }
1462                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "earlyBindingMCS",
1463                                System.identityHashCode(mHandler));
1464                    }
1465                    break;
1466                case INIT_COPY: {
1467                    HandlerParams params = (HandlerParams) msg.obj;
1468                    int idx = mPendingInstalls.size();
1469                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1470                    // If a bind was already initiated we dont really
1471                    // need to do anything. The pending install
1472                    // will be processed later on.
1473                    if (!mBound) {
1474                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1475                                System.identityHashCode(mHandler));
1476                        // If this is the only one pending we might
1477                        // have to bind to the service again.
1478                        if (!connectToService()) {
1479                            Slog.e(TAG, "Failed to bind to media container service");
1480                            params.serviceError();
1481                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1482                                    System.identityHashCode(mHandler));
1483                            if (params.traceMethod != null) {
1484                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1485                                        params.traceCookie);
1486                            }
1487                            return;
1488                        } else {
1489                            // Once we bind to the service, the first
1490                            // pending request will be processed.
1491                            mPendingInstalls.add(idx, params);
1492                        }
1493                    } else {
1494                        mPendingInstalls.add(idx, params);
1495                        // Already bound to the service. Just make
1496                        // sure we trigger off processing the first request.
1497                        if (idx == 0) {
1498                            mHandler.sendEmptyMessage(MCS_BOUND);
1499                        }
1500                    }
1501                    break;
1502                }
1503                case MCS_BOUND: {
1504                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1505                    if (msg.obj != null) {
1506                        mContainerService = (IMediaContainerService) msg.obj;
1507                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1508                                System.identityHashCode(mHandler));
1509                    }
1510                    if (mContainerService == null) {
1511                        if (!mBound) {
1512                            // Something seriously wrong since we are not bound and we are not
1513                            // waiting for connection. Bail out.
1514                            Slog.e(TAG, "Cannot bind to media container service");
1515                            for (HandlerParams params : mPendingInstalls) {
1516                                // Indicate service bind error
1517                                params.serviceError();
1518                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1519                                        System.identityHashCode(params));
1520                                if (params.traceMethod != null) {
1521                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1522                                            params.traceMethod, params.traceCookie);
1523                                }
1524                            }
1525                            mPendingInstalls.clear();
1526                        } else {
1527                            Slog.w(TAG, "Waiting to connect to media container service");
1528                        }
1529                    } else if (mPendingInstalls.size() > 0) {
1530                        HandlerParams params = mPendingInstalls.get(0);
1531                        if (params != null) {
1532                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1533                                    System.identityHashCode(params));
1534                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1535                            if (params.startCopy()) {
1536                                // We are done...  look for more work or to
1537                                // go idle.
1538                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1539                                        "Checking for more work or unbind...");
1540                                // Delete pending install
1541                                if (mPendingInstalls.size() > 0) {
1542                                    mPendingInstalls.remove(0);
1543                                }
1544                                if (mPendingInstalls.size() == 0) {
1545                                    if (mBound) {
1546                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1547                                                "Posting delayed MCS_UNBIND");
1548                                        removeMessages(MCS_UNBIND);
1549                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1550                                        // Unbind after a little delay, to avoid
1551                                        // continual thrashing.
1552                                        sendMessageDelayed(ubmsg, 10000);
1553                                    }
1554                                } else {
1555                                    // There are more pending requests in queue.
1556                                    // Just post MCS_BOUND message to trigger processing
1557                                    // of next pending install.
1558                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1559                                            "Posting MCS_BOUND for next work");
1560                                    mHandler.sendEmptyMessage(MCS_BOUND);
1561                                }
1562                            }
1563                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1564                        }
1565                    } else {
1566                        // Should never happen ideally.
1567                        Slog.w(TAG, "Empty queue");
1568                    }
1569                    break;
1570                }
1571                case MCS_RECONNECT: {
1572                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1573                    if (mPendingInstalls.size() > 0) {
1574                        if (mBound) {
1575                            disconnectService();
1576                        }
1577                        if (!connectToService()) {
1578                            Slog.e(TAG, "Failed to bind to media container service");
1579                            for (HandlerParams params : mPendingInstalls) {
1580                                // Indicate service bind error
1581                                params.serviceError();
1582                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1583                                        System.identityHashCode(params));
1584                            }
1585                            mPendingInstalls.clear();
1586                        }
1587                    }
1588                    break;
1589                }
1590                case MCS_UNBIND: {
1591                    // If there is no actual work left, then time to unbind.
1592                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1593
1594                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1595                        if (mBound) {
1596                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1597
1598                            disconnectService();
1599                        }
1600                    } else if (mPendingInstalls.size() > 0) {
1601                        // There are more pending requests in queue.
1602                        // Just post MCS_BOUND message to trigger processing
1603                        // of next pending install.
1604                        mHandler.sendEmptyMessage(MCS_BOUND);
1605                    }
1606
1607                    break;
1608                }
1609                case MCS_GIVE_UP: {
1610                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1611                    HandlerParams params = mPendingInstalls.remove(0);
1612                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1613                            System.identityHashCode(params));
1614                    break;
1615                }
1616                case SEND_PENDING_BROADCAST: {
1617                    String packages[];
1618                    ArrayList<String> components[];
1619                    int size = 0;
1620                    int uids[];
1621                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1622                    synchronized (mPackages) {
1623                        if (mPendingBroadcasts == null) {
1624                            return;
1625                        }
1626                        size = mPendingBroadcasts.size();
1627                        if (size <= 0) {
1628                            // Nothing to be done. Just return
1629                            return;
1630                        }
1631                        packages = new String[size];
1632                        components = new ArrayList[size];
1633                        uids = new int[size];
1634                        int i = 0;  // filling out the above arrays
1635
1636                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1637                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1638                            Iterator<Map.Entry<String, ArrayList<String>>> it
1639                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1640                                            .entrySet().iterator();
1641                            while (it.hasNext() && i < size) {
1642                                Map.Entry<String, ArrayList<String>> ent = it.next();
1643                                packages[i] = ent.getKey();
1644                                components[i] = ent.getValue();
1645                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1646                                uids[i] = (ps != null)
1647                                        ? UserHandle.getUid(packageUserId, ps.appId)
1648                                        : -1;
1649                                i++;
1650                            }
1651                        }
1652                        size = i;
1653                        mPendingBroadcasts.clear();
1654                    }
1655                    // Send broadcasts
1656                    for (int i = 0; i < size; i++) {
1657                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1658                    }
1659                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1660                    break;
1661                }
1662                case START_CLEANING_PACKAGE: {
1663                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1664                    final String packageName = (String)msg.obj;
1665                    final int userId = msg.arg1;
1666                    final boolean andCode = msg.arg2 != 0;
1667                    synchronized (mPackages) {
1668                        if (userId == UserHandle.USER_ALL) {
1669                            int[] users = sUserManager.getUserIds();
1670                            for (int user : users) {
1671                                mSettings.addPackageToCleanLPw(
1672                                        new PackageCleanItem(user, packageName, andCode));
1673                            }
1674                        } else {
1675                            mSettings.addPackageToCleanLPw(
1676                                    new PackageCleanItem(userId, packageName, andCode));
1677                        }
1678                    }
1679                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1680                    startCleaningPackages();
1681                } break;
1682                case POST_INSTALL: {
1683                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1684
1685                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1686                    final boolean didRestore = (msg.arg2 != 0);
1687                    mRunningInstalls.delete(msg.arg1);
1688
1689                    if (data != null) {
1690                        InstallArgs args = data.args;
1691                        PackageInstalledInfo parentRes = data.res;
1692
1693                        final boolean grantPermissions = (args.installFlags
1694                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1695                        final boolean killApp = (args.installFlags
1696                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1697                        final boolean virtualPreload = ((args.installFlags
1698                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1699                        final String[] grantedPermissions = args.installGrantPermissions;
1700
1701                        // Handle the parent package
1702                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1703                                virtualPreload, grantedPermissions, didRestore,
1704                                args.installerPackageName, args.observer);
1705
1706                        // Handle the child packages
1707                        final int childCount = (parentRes.addedChildPackages != null)
1708                                ? parentRes.addedChildPackages.size() : 0;
1709                        for (int i = 0; i < childCount; i++) {
1710                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1711                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1712                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1713                                    args.installerPackageName, args.observer);
1714                        }
1715
1716                        // Log tracing if needed
1717                        if (args.traceMethod != null) {
1718                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1719                                    args.traceCookie);
1720                        }
1721                    } else {
1722                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1723                    }
1724
1725                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1726                } break;
1727                case WRITE_SETTINGS: {
1728                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1729                    synchronized (mPackages) {
1730                        removeMessages(WRITE_SETTINGS);
1731                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1732                        mSettings.writeLPr();
1733                        mDirtyUsers.clear();
1734                    }
1735                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1736                } break;
1737                case WRITE_PACKAGE_RESTRICTIONS: {
1738                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1739                    synchronized (mPackages) {
1740                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1741                        for (int userId : mDirtyUsers) {
1742                            mSettings.writePackageRestrictionsLPr(userId);
1743                        }
1744                        mDirtyUsers.clear();
1745                    }
1746                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1747                } break;
1748                case WRITE_PACKAGE_LIST: {
1749                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1750                    synchronized (mPackages) {
1751                        removeMessages(WRITE_PACKAGE_LIST);
1752                        mSettings.writePackageListLPr(msg.arg1);
1753                    }
1754                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1755                } break;
1756                case CHECK_PENDING_VERIFICATION: {
1757                    final int verificationId = msg.arg1;
1758                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1759
1760                    if ((state != null) && !state.timeoutExtended()) {
1761                        final InstallArgs args = state.getInstallArgs();
1762                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1763
1764                        Slog.i(TAG, "Verification timed out for " + originUri);
1765                        mPendingVerification.remove(verificationId);
1766
1767                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1768
1769                        final UserHandle user = args.getUser();
1770                        if (getDefaultVerificationResponse(user)
1771                                == PackageManager.VERIFICATION_ALLOW) {
1772                            Slog.i(TAG, "Continuing with installation of " + originUri);
1773                            state.setVerifierResponse(Binder.getCallingUid(),
1774                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1775                            broadcastPackageVerified(verificationId, originUri,
1776                                    PackageManager.VERIFICATION_ALLOW, user);
1777                            try {
1778                                ret = args.copyApk(mContainerService, true);
1779                            } catch (RemoteException e) {
1780                                Slog.e(TAG, "Could not contact the ContainerService");
1781                            }
1782                        } else {
1783                            broadcastPackageVerified(verificationId, originUri,
1784                                    PackageManager.VERIFICATION_REJECT, user);
1785                        }
1786
1787                        Trace.asyncTraceEnd(
1788                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1789
1790                        processPendingInstall(args, ret);
1791                        mHandler.sendEmptyMessage(MCS_UNBIND);
1792                    }
1793                    break;
1794                }
1795                case PACKAGE_VERIFIED: {
1796                    final int verificationId = msg.arg1;
1797
1798                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1799                    if (state == null) {
1800                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1801                        break;
1802                    }
1803
1804                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1805
1806                    state.setVerifierResponse(response.callerUid, response.code);
1807
1808                    if (state.isVerificationComplete()) {
1809                        mPendingVerification.remove(verificationId);
1810
1811                        final InstallArgs args = state.getInstallArgs();
1812                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1813
1814                        int ret;
1815                        if (state.isInstallAllowed()) {
1816                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1817                            broadcastPackageVerified(verificationId, originUri,
1818                                    response.code, state.getInstallArgs().getUser());
1819                            try {
1820                                ret = args.copyApk(mContainerService, true);
1821                            } catch (RemoteException e) {
1822                                Slog.e(TAG, "Could not contact the ContainerService");
1823                            }
1824                        } else {
1825                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1826                        }
1827
1828                        Trace.asyncTraceEnd(
1829                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1830
1831                        processPendingInstall(args, ret);
1832                        mHandler.sendEmptyMessage(MCS_UNBIND);
1833                    }
1834
1835                    break;
1836                }
1837                case START_INTENT_FILTER_VERIFICATIONS: {
1838                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1839                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1840                            params.replacing, params.pkg);
1841                    break;
1842                }
1843                case INTENT_FILTER_VERIFIED: {
1844                    final int verificationId = msg.arg1;
1845
1846                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1847                            verificationId);
1848                    if (state == null) {
1849                        Slog.w(TAG, "Invalid IntentFilter verification token "
1850                                + verificationId + " received");
1851                        break;
1852                    }
1853
1854                    final int userId = state.getUserId();
1855
1856                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1857                            "Processing IntentFilter verification with token:"
1858                            + verificationId + " and userId:" + userId);
1859
1860                    final IntentFilterVerificationResponse response =
1861                            (IntentFilterVerificationResponse) msg.obj;
1862
1863                    state.setVerifierResponse(response.callerUid, response.code);
1864
1865                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1866                            "IntentFilter verification with token:" + verificationId
1867                            + " and userId:" + userId
1868                            + " is settings verifier response with response code:"
1869                            + response.code);
1870
1871                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1872                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1873                                + response.getFailedDomainsString());
1874                    }
1875
1876                    if (state.isVerificationComplete()) {
1877                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1878                    } else {
1879                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1880                                "IntentFilter verification with token:" + verificationId
1881                                + " was not said to be complete");
1882                    }
1883
1884                    break;
1885                }
1886                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1887                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1888                            mInstantAppResolverConnection,
1889                            (InstantAppRequest) msg.obj,
1890                            mInstantAppInstallerActivity,
1891                            mHandler);
1892                }
1893            }
1894        }
1895    }
1896
1897    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1898        @Override
1899        public void onGidsChanged(int appId, int userId) {
1900            mHandler.post(new Runnable() {
1901                @Override
1902                public void run() {
1903                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1904                }
1905            });
1906        }
1907        @Override
1908        public void onPermissionGranted(int uid, int userId) {
1909            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1910
1911            // Not critical; if this is lost, the application has to request again.
1912            synchronized (mPackages) {
1913                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1914            }
1915        }
1916        @Override
1917        public void onInstallPermissionGranted() {
1918            synchronized (mPackages) {
1919                scheduleWriteSettingsLocked();
1920            }
1921        }
1922        @Override
1923        public void onPermissionRevoked(int uid, int userId) {
1924            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1925
1926            synchronized (mPackages) {
1927                // Critical; after this call the application should never have the permission
1928                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1929            }
1930
1931            final int appId = UserHandle.getAppId(uid);
1932            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1933        }
1934        @Override
1935        public void onInstallPermissionRevoked() {
1936            synchronized (mPackages) {
1937                scheduleWriteSettingsLocked();
1938            }
1939        }
1940        @Override
1941        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1942            synchronized (mPackages) {
1943                for (int userId : updatedUserIds) {
1944                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1945                }
1946            }
1947        }
1948        @Override
1949        public void onInstallPermissionUpdated() {
1950            synchronized (mPackages) {
1951                scheduleWriteSettingsLocked();
1952            }
1953        }
1954        @Override
1955        public void onPermissionRemoved() {
1956            synchronized (mPackages) {
1957                mSettings.writeLPr();
1958            }
1959        }
1960    };
1961
1962    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1963            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1964            boolean launchedForRestore, String installerPackage,
1965            IPackageInstallObserver2 installObserver) {
1966        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1967            // Send the removed broadcasts
1968            if (res.removedInfo != null) {
1969                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1970            }
1971
1972            // Now that we successfully installed the package, grant runtime
1973            // permissions if requested before broadcasting the install. Also
1974            // for legacy apps in permission review mode we clear the permission
1975            // review flag which is used to emulate runtime permissions for
1976            // legacy apps.
1977            if (grantPermissions) {
1978                final int callingUid = Binder.getCallingUid();
1979                mPermissionManager.grantRequestedRuntimePermissions(
1980                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1981                        mPermissionCallback);
1982            }
1983
1984            final boolean update = res.removedInfo != null
1985                    && res.removedInfo.removedPackage != null;
1986            final String installerPackageName =
1987                    res.installerPackageName != null
1988                            ? res.installerPackageName
1989                            : res.removedInfo != null
1990                                    ? res.removedInfo.installerPackageName
1991                                    : null;
1992
1993            // If this is the first time we have child packages for a disabled privileged
1994            // app that had no children, we grant requested runtime permissions to the new
1995            // children if the parent on the system image had them already granted.
1996            if (res.pkg.parentPackage != null) {
1997                final int callingUid = Binder.getCallingUid();
1998                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1999                        res.pkg, callingUid, mPermissionCallback);
2000            }
2001
2002            synchronized (mPackages) {
2003                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
2004            }
2005
2006            final String packageName = res.pkg.applicationInfo.packageName;
2007
2008            // Determine the set of users who are adding this package for
2009            // the first time vs. those who are seeing an update.
2010            int[] firstUserIds = EMPTY_INT_ARRAY;
2011            int[] firstInstantUserIds = EMPTY_INT_ARRAY;
2012            int[] updateUserIds = EMPTY_INT_ARRAY;
2013            int[] instantUserIds = EMPTY_INT_ARRAY;
2014            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
2015            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
2016            for (int newUser : res.newUsers) {
2017                final boolean isInstantApp = ps.getInstantApp(newUser);
2018                if (allNewUsers) {
2019                    if (isInstantApp) {
2020                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2021                    } else {
2022                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2023                    }
2024                    continue;
2025                }
2026                boolean isNew = true;
2027                for (int origUser : res.origUsers) {
2028                    if (origUser == newUser) {
2029                        isNew = false;
2030                        break;
2031                    }
2032                }
2033                if (isNew) {
2034                    if (isInstantApp) {
2035                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2036                    } else {
2037                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2038                    }
2039                } else {
2040                    if (isInstantApp) {
2041                        instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser);
2042                    } else {
2043                        updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser);
2044                    }
2045                }
2046            }
2047
2048            // Send installed broadcasts if the package is not a static shared lib.
2049            if (res.pkg.staticSharedLibName == null) {
2050                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2051
2052                // Send added for users that see the package for the first time
2053                // sendPackageAddedForNewUsers also deals with system apps
2054                int appId = UserHandle.getAppId(res.uid);
2055                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2056                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2057                        virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds);
2058
2059                // Send added for users that don't see the package for the first time
2060                Bundle extras = new Bundle(1);
2061                extras.putInt(Intent.EXTRA_UID, res.uid);
2062                if (update) {
2063                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2064                }
2065                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2066                        extras, 0 /*flags*/,
2067                        null /*targetPackage*/, null /*finishedReceiver*/,
2068                        updateUserIds, instantUserIds);
2069                if (installerPackageName != null) {
2070                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2071                            extras, 0 /*flags*/,
2072                            installerPackageName, null /*finishedReceiver*/,
2073                            updateUserIds, instantUserIds);
2074                }
2075
2076                // Send replaced for users that don't see the package for the first time
2077                if (update) {
2078                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2079                            packageName, extras, 0 /*flags*/,
2080                            null /*targetPackage*/, null /*finishedReceiver*/,
2081                            updateUserIds, instantUserIds);
2082                    if (installerPackageName != null) {
2083                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2084                                extras, 0 /*flags*/,
2085                                installerPackageName, null /*finishedReceiver*/,
2086                                updateUserIds, instantUserIds);
2087                    }
2088                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2089                            null /*package*/, null /*extras*/, 0 /*flags*/,
2090                            packageName /*targetPackage*/,
2091                            null /*finishedReceiver*/, updateUserIds, instantUserIds);
2092                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2093                    // First-install and we did a restore, so we're responsible for the
2094                    // first-launch broadcast.
2095                    if (DEBUG_BACKUP) {
2096                        Slog.i(TAG, "Post-restore of " + packageName
2097                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds));
2098                    }
2099                    sendFirstLaunchBroadcast(packageName, installerPackage,
2100                            firstUserIds, firstInstantUserIds);
2101                }
2102
2103                // Send broadcast package appeared if forward locked/external for all users
2104                // treat asec-hosted packages like removable media on upgrade
2105                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2106                    if (DEBUG_INSTALL) {
2107                        Slog.i(TAG, "upgrading pkg " + res.pkg
2108                                + " is ASEC-hosted -> AVAILABLE");
2109                    }
2110                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2111                    ArrayList<String> pkgList = new ArrayList<>(1);
2112                    pkgList.add(packageName);
2113                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2114                }
2115            }
2116
2117            // Work that needs to happen on first install within each user
2118            if (firstUserIds != null && firstUserIds.length > 0) {
2119                synchronized (mPackages) {
2120                    for (int userId : firstUserIds) {
2121                        // If this app is a browser and it's newly-installed for some
2122                        // users, clear any default-browser state in those users. The
2123                        // app's nature doesn't depend on the user, so we can just check
2124                        // its browser nature in any user and generalize.
2125                        if (packageIsBrowser(packageName, userId)) {
2126                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2127                        }
2128
2129                        // We may also need to apply pending (restored) runtime
2130                        // permission grants within these users.
2131                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2132                    }
2133                }
2134            }
2135
2136            if (allNewUsers && !update) {
2137                notifyPackageAdded(packageName);
2138            }
2139
2140            // Log current value of "unknown sources" setting
2141            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2142                    getUnknownSourcesSettings());
2143
2144            // Remove the replaced package's older resources safely now
2145            // We delete after a gc for applications  on sdcard.
2146            if (res.removedInfo != null && res.removedInfo.args != null) {
2147                Runtime.getRuntime().gc();
2148                synchronized (mInstallLock) {
2149                    res.removedInfo.args.doPostDeleteLI(true);
2150                }
2151            } else {
2152                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2153                // and not block here.
2154                VMRuntime.getRuntime().requestConcurrentGC();
2155            }
2156
2157            // Notify DexManager that the package was installed for new users.
2158            // The updated users should already be indexed and the package code paths
2159            // should not change.
2160            // Don't notify the manager for ephemeral apps as they are not expected to
2161            // survive long enough to benefit of background optimizations.
2162            for (int userId : firstUserIds) {
2163                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2164                // There's a race currently where some install events may interleave with an uninstall.
2165                // This can lead to package info being null (b/36642664).
2166                if (info != null) {
2167                    mDexManager.notifyPackageInstalled(info, userId);
2168                }
2169            }
2170        }
2171
2172        // If someone is watching installs - notify them
2173        if (installObserver != null) {
2174            try {
2175                Bundle extras = extrasForInstallResult(res);
2176                installObserver.onPackageInstalled(res.name, res.returnCode,
2177                        res.returnMsg, extras);
2178            } catch (RemoteException e) {
2179                Slog.i(TAG, "Observer no longer exists.");
2180            }
2181        }
2182    }
2183
2184    private StorageEventListener mStorageListener = new StorageEventListener() {
2185        @Override
2186        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2187            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2188                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2189                    final String volumeUuid = vol.getFsUuid();
2190
2191                    // Clean up any users or apps that were removed or recreated
2192                    // while this volume was missing
2193                    sUserManager.reconcileUsers(volumeUuid);
2194                    reconcileApps(volumeUuid);
2195
2196                    // Clean up any install sessions that expired or were
2197                    // cancelled while this volume was missing
2198                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2199
2200                    loadPrivatePackages(vol);
2201
2202                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2203                    unloadPrivatePackages(vol);
2204                }
2205            }
2206        }
2207
2208        @Override
2209        public void onVolumeForgotten(String fsUuid) {
2210            if (TextUtils.isEmpty(fsUuid)) {
2211                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2212                return;
2213            }
2214
2215            // Remove any apps installed on the forgotten volume
2216            synchronized (mPackages) {
2217                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2218                for (PackageSetting ps : packages) {
2219                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2220                    deletePackageVersioned(new VersionedPackage(ps.name,
2221                            PackageManager.VERSION_CODE_HIGHEST),
2222                            new LegacyPackageDeleteObserver(null).getBinder(),
2223                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2224                    // Try very hard to release any references to this package
2225                    // so we don't risk the system server being killed due to
2226                    // open FDs
2227                    AttributeCache.instance().removePackage(ps.name);
2228                }
2229
2230                mSettings.onVolumeForgotten(fsUuid);
2231                mSettings.writeLPr();
2232            }
2233        }
2234    };
2235
2236    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2237        Bundle extras = null;
2238        switch (res.returnCode) {
2239            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2240                extras = new Bundle();
2241                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2242                        res.origPermission);
2243                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2244                        res.origPackage);
2245                break;
2246            }
2247            case PackageManager.INSTALL_SUCCEEDED: {
2248                extras = new Bundle();
2249                extras.putBoolean(Intent.EXTRA_REPLACING,
2250                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2251                break;
2252            }
2253        }
2254        return extras;
2255    }
2256
2257    void scheduleWriteSettingsLocked() {
2258        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2259            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2260        }
2261    }
2262
2263    void scheduleWritePackageListLocked(int userId) {
2264        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2265            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2266            msg.arg1 = userId;
2267            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2268        }
2269    }
2270
2271    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2272        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2273        scheduleWritePackageRestrictionsLocked(userId);
2274    }
2275
2276    void scheduleWritePackageRestrictionsLocked(int userId) {
2277        final int[] userIds = (userId == UserHandle.USER_ALL)
2278                ? sUserManager.getUserIds() : new int[]{userId};
2279        for (int nextUserId : userIds) {
2280            if (!sUserManager.exists(nextUserId)) return;
2281            mDirtyUsers.add(nextUserId);
2282            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2283                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2284            }
2285        }
2286    }
2287
2288    public static PackageManagerService main(Context context, Installer installer,
2289            boolean factoryTest, boolean onlyCore) {
2290        // Self-check for initial settings.
2291        PackageManagerServiceCompilerMapping.checkProperties();
2292
2293        PackageManagerService m = new PackageManagerService(context, installer,
2294                factoryTest, onlyCore);
2295        m.enableSystemUserPackages();
2296        ServiceManager.addService("package", m);
2297        final PackageManagerNative pmn = m.new PackageManagerNative();
2298        ServiceManager.addService("package_native", pmn);
2299        return m;
2300    }
2301
2302    private void enableSystemUserPackages() {
2303        if (!UserManager.isSplitSystemUser()) {
2304            return;
2305        }
2306        // For system user, enable apps based on the following conditions:
2307        // - app is whitelisted or belong to one of these groups:
2308        //   -- system app which has no launcher icons
2309        //   -- system app which has INTERACT_ACROSS_USERS permission
2310        //   -- system IME app
2311        // - app is not in the blacklist
2312        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2313        Set<String> enableApps = new ArraySet<>();
2314        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2315                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2316                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2317        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2318        enableApps.addAll(wlApps);
2319        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2320                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2321        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2322        enableApps.removeAll(blApps);
2323        Log.i(TAG, "Applications installed for system user: " + enableApps);
2324        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2325                UserHandle.SYSTEM);
2326        final int allAppsSize = allAps.size();
2327        synchronized (mPackages) {
2328            for (int i = 0; i < allAppsSize; i++) {
2329                String pName = allAps.get(i);
2330                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2331                // Should not happen, but we shouldn't be failing if it does
2332                if (pkgSetting == null) {
2333                    continue;
2334                }
2335                boolean install = enableApps.contains(pName);
2336                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2337                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2338                            + " for system user");
2339                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2340                }
2341            }
2342            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2343        }
2344    }
2345
2346    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2347        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2348                Context.DISPLAY_SERVICE);
2349        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2350    }
2351
2352    /**
2353     * Requests that files preopted on a secondary system partition be copied to the data partition
2354     * if possible.  Note that the actual copying of the files is accomplished by init for security
2355     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2356     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2357     */
2358    private static void requestCopyPreoptedFiles() {
2359        final int WAIT_TIME_MS = 100;
2360        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2361        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2362            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2363            // We will wait for up to 100 seconds.
2364            final long timeStart = SystemClock.uptimeMillis();
2365            final long timeEnd = timeStart + 100 * 1000;
2366            long timeNow = timeStart;
2367            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2368                try {
2369                    Thread.sleep(WAIT_TIME_MS);
2370                } catch (InterruptedException e) {
2371                    // Do nothing
2372                }
2373                timeNow = SystemClock.uptimeMillis();
2374                if (timeNow > timeEnd) {
2375                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2376                    Slog.wtf(TAG, "cppreopt did not finish!");
2377                    break;
2378                }
2379            }
2380
2381            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2382        }
2383    }
2384
2385    public PackageManagerService(Context context, Installer installer,
2386            boolean factoryTest, boolean onlyCore) {
2387        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2388        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2389        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2390                SystemClock.uptimeMillis());
2391
2392        if (mSdkVersion <= 0) {
2393            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2394        }
2395
2396        mContext = context;
2397
2398        mFactoryTest = factoryTest;
2399        mOnlyCore = onlyCore;
2400        mMetrics = new DisplayMetrics();
2401        mInstaller = installer;
2402
2403        // Create sub-components that provide services / data. Order here is important.
2404        synchronized (mInstallLock) {
2405        synchronized (mPackages) {
2406            // Expose private service for system components to use.
2407            LocalServices.addService(
2408                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2409            sUserManager = new UserManagerService(context, this,
2410                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2411            mPermissionManager = PermissionManagerService.create(context,
2412                    new DefaultPermissionGrantedCallback() {
2413                        @Override
2414                        public void onDefaultRuntimePermissionsGranted(int userId) {
2415                            synchronized(mPackages) {
2416                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2417                            }
2418                        }
2419                    }, mPackages /*externalLock*/);
2420            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2421            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2422        }
2423        }
2424        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2425                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2426        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2427                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2428        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2429                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2430        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2431                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2432        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2433                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2434        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2435                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2436        mSettings.addSharedUserLPw("android.uid.se", SE_UID,
2437                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2438
2439        String separateProcesses = SystemProperties.get("debug.separate_processes");
2440        if (separateProcesses != null && separateProcesses.length() > 0) {
2441            if ("*".equals(separateProcesses)) {
2442                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2443                mSeparateProcesses = null;
2444                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2445            } else {
2446                mDefParseFlags = 0;
2447                mSeparateProcesses = separateProcesses.split(",");
2448                Slog.w(TAG, "Running with debug.separate_processes: "
2449                        + separateProcesses);
2450            }
2451        } else {
2452            mDefParseFlags = 0;
2453            mSeparateProcesses = null;
2454        }
2455
2456        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2457                "*dexopt*");
2458        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2459                installer, mInstallLock);
2460        mDexManager = new DexManager(mContext, this, mPackageDexOptimizer, installer, mInstallLock,
2461                dexManagerListener);
2462        mArtManagerService = new ArtManagerService(mContext, this, installer, mInstallLock);
2463        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2464
2465        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2466                FgThread.get().getLooper());
2467
2468        getDefaultDisplayMetrics(context, mMetrics);
2469
2470        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2471        SystemConfig systemConfig = SystemConfig.getInstance();
2472        mAvailableFeatures = systemConfig.getAvailableFeatures();
2473        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2474
2475        mProtectedPackages = new ProtectedPackages(mContext);
2476
2477        synchronized (mInstallLock) {
2478        // writer
2479        synchronized (mPackages) {
2480            mHandlerThread = new ServiceThread(TAG,
2481                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2482            mHandlerThread.start();
2483            mHandler = new PackageHandler(mHandlerThread.getLooper());
2484            mProcessLoggingHandler = new ProcessLoggingHandler();
2485            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2486            mInstantAppRegistry = new InstantAppRegistry(this);
2487
2488            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2489            final int builtInLibCount = libConfig.size();
2490            for (int i = 0; i < builtInLibCount; i++) {
2491                String name = libConfig.keyAt(i);
2492                String path = libConfig.valueAt(i);
2493                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2494                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2495            }
2496
2497            SELinuxMMAC.readInstallPolicy();
2498
2499            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2500            FallbackCategoryProvider.loadFallbacks();
2501            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2502
2503            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2504            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2505            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2506
2507            // Clean up orphaned packages for which the code path doesn't exist
2508            // and they are an update to a system app - caused by bug/32321269
2509            final int packageSettingCount = mSettings.mPackages.size();
2510            for (int i = packageSettingCount - 1; i >= 0; i--) {
2511                PackageSetting ps = mSettings.mPackages.valueAt(i);
2512                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2513                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2514                    mSettings.mPackages.removeAt(i);
2515                    mSettings.enableSystemPackageLPw(ps.name);
2516                }
2517            }
2518
2519            if (mFirstBoot) {
2520                requestCopyPreoptedFiles();
2521            }
2522
2523            String customResolverActivity = Resources.getSystem().getString(
2524                    R.string.config_customResolverActivity);
2525            if (TextUtils.isEmpty(customResolverActivity)) {
2526                customResolverActivity = null;
2527            } else {
2528                mCustomResolverComponentName = ComponentName.unflattenFromString(
2529                        customResolverActivity);
2530            }
2531
2532            long startTime = SystemClock.uptimeMillis();
2533
2534            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2535                    startTime);
2536
2537            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2538            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2539
2540            if (bootClassPath == null) {
2541                Slog.w(TAG, "No BOOTCLASSPATH found!");
2542            }
2543
2544            if (systemServerClassPath == null) {
2545                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2546            }
2547
2548            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2549
2550            final VersionInfo ver = mSettings.getInternalVersion();
2551            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2552            if (mIsUpgrade) {
2553                logCriticalInfo(Log.INFO,
2554                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2555            }
2556
2557            // when upgrading from pre-M, promote system app permissions from install to runtime
2558            mPromoteSystemApps =
2559                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2560
2561            // When upgrading from pre-N, we need to handle package extraction like first boot,
2562            // as there is no profiling data available.
2563            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2564
2565            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2566
2567            // save off the names of pre-existing system packages prior to scanning; we don't
2568            // want to automatically grant runtime permissions for new system apps
2569            if (mPromoteSystemApps) {
2570                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2571                while (pkgSettingIter.hasNext()) {
2572                    PackageSetting ps = pkgSettingIter.next();
2573                    if (isSystemApp(ps)) {
2574                        mExistingSystemPackages.add(ps.name);
2575                    }
2576                }
2577            }
2578
2579            mCacheDir = preparePackageParserCache(mIsUpgrade);
2580
2581            // Set flag to monitor and not change apk file paths when
2582            // scanning install directories.
2583            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2584
2585            if (mIsUpgrade || mFirstBoot) {
2586                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2587            }
2588
2589            // Collect vendor/product overlay packages. (Do this before scanning any apps.)
2590            // For security and version matching reason, only consider
2591            // overlay packages if they reside in the right directory.
2592            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2593                    mDefParseFlags
2594                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2595                    scanFlags
2596                    | SCAN_AS_SYSTEM
2597                    | SCAN_AS_VENDOR,
2598                    0);
2599            scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR),
2600                    mDefParseFlags
2601                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2602                    scanFlags
2603                    | SCAN_AS_SYSTEM
2604                    | SCAN_AS_PRODUCT,
2605                    0);
2606
2607            mParallelPackageParserCallback.findStaticOverlayPackages();
2608
2609            // Find base frameworks (resource packages without code).
2610            scanDirTracedLI(frameworkDir,
2611                    mDefParseFlags
2612                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2613                    scanFlags
2614                    | SCAN_NO_DEX
2615                    | SCAN_AS_SYSTEM
2616                    | SCAN_AS_PRIVILEGED,
2617                    0);
2618
2619            // Collect privileged system packages.
2620            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2621            scanDirTracedLI(privilegedAppDir,
2622                    mDefParseFlags
2623                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2624                    scanFlags
2625                    | SCAN_AS_SYSTEM
2626                    | SCAN_AS_PRIVILEGED,
2627                    0);
2628
2629            // Collect ordinary system packages.
2630            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2631            scanDirTracedLI(systemAppDir,
2632                    mDefParseFlags
2633                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2634                    scanFlags
2635                    | SCAN_AS_SYSTEM,
2636                    0);
2637
2638            // Collect privileged vendor packages.
2639            File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
2640            try {
2641                privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
2642            } catch (IOException e) {
2643                // failed to look up canonical path, continue with original one
2644            }
2645            scanDirTracedLI(privilegedVendorAppDir,
2646                    mDefParseFlags
2647                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2648                    scanFlags
2649                    | SCAN_AS_SYSTEM
2650                    | SCAN_AS_VENDOR
2651                    | SCAN_AS_PRIVILEGED,
2652                    0);
2653
2654            // Collect ordinary vendor packages.
2655            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2656            try {
2657                vendorAppDir = vendorAppDir.getCanonicalFile();
2658            } catch (IOException e) {
2659                // failed to look up canonical path, continue with original one
2660            }
2661            scanDirTracedLI(vendorAppDir,
2662                    mDefParseFlags
2663                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2664                    scanFlags
2665                    | SCAN_AS_SYSTEM
2666                    | SCAN_AS_VENDOR,
2667                    0);
2668
2669            // Collect privileged odm packages. /odm is another vendor partition
2670            // other than /vendor.
2671            File privilegedOdmAppDir = new File(Environment.getOdmDirectory(),
2672                        "priv-app");
2673            try {
2674                privilegedOdmAppDir = privilegedOdmAppDir.getCanonicalFile();
2675            } catch (IOException e) {
2676                // failed to look up canonical path, continue with original one
2677            }
2678            scanDirTracedLI(privilegedOdmAppDir,
2679                    mDefParseFlags
2680                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2681                    scanFlags
2682                    | SCAN_AS_SYSTEM
2683                    | SCAN_AS_VENDOR
2684                    | SCAN_AS_PRIVILEGED,
2685                    0);
2686
2687            // Collect ordinary odm packages. /odm is another vendor partition
2688            // other than /vendor.
2689            File odmAppDir = new File(Environment.getOdmDirectory(), "app");
2690            try {
2691                odmAppDir = odmAppDir.getCanonicalFile();
2692            } catch (IOException e) {
2693                // failed to look up canonical path, continue with original one
2694            }
2695            scanDirTracedLI(odmAppDir,
2696                    mDefParseFlags
2697                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2698                    scanFlags
2699                    | SCAN_AS_SYSTEM
2700                    | SCAN_AS_VENDOR,
2701                    0);
2702
2703            // Collect all OEM packages.
2704            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2705            scanDirTracedLI(oemAppDir,
2706                    mDefParseFlags
2707                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2708                    scanFlags
2709                    | SCAN_AS_SYSTEM
2710                    | SCAN_AS_OEM,
2711                    0);
2712
2713            // Collected privileged product packages.
2714            File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
2715            try {
2716                privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile();
2717            } catch (IOException e) {
2718                // failed to look up canonical path, continue with original one
2719            }
2720            scanDirTracedLI(privilegedProductAppDir,
2721                    mDefParseFlags
2722                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2723                    scanFlags
2724                    | SCAN_AS_SYSTEM
2725                    | SCAN_AS_PRODUCT
2726                    | SCAN_AS_PRIVILEGED,
2727                    0);
2728
2729            // Collect ordinary product packages.
2730            File productAppDir = new File(Environment.getProductDirectory(), "app");
2731            try {
2732                productAppDir = productAppDir.getCanonicalFile();
2733            } catch (IOException e) {
2734                // failed to look up canonical path, continue with original one
2735            }
2736            scanDirTracedLI(productAppDir,
2737                    mDefParseFlags
2738                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2739                    scanFlags
2740                    | SCAN_AS_SYSTEM
2741                    | SCAN_AS_PRODUCT,
2742                    0);
2743
2744            // Prune any system packages that no longer exist.
2745            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2746            // Stub packages must either be replaced with full versions in the /data
2747            // partition or be disabled.
2748            final List<String> stubSystemApps = new ArrayList<>();
2749            if (!mOnlyCore) {
2750                // do this first before mucking with mPackages for the "expecting better" case
2751                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2752                while (pkgIterator.hasNext()) {
2753                    final PackageParser.Package pkg = pkgIterator.next();
2754                    if (pkg.isStub) {
2755                        stubSystemApps.add(pkg.packageName);
2756                    }
2757                }
2758
2759                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2760                while (psit.hasNext()) {
2761                    PackageSetting ps = psit.next();
2762
2763                    /*
2764                     * If this is not a system app, it can't be a
2765                     * disable system app.
2766                     */
2767                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2768                        continue;
2769                    }
2770
2771                    /*
2772                     * If the package is scanned, it's not erased.
2773                     */
2774                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2775                    if (scannedPkg != null) {
2776                        /*
2777                         * If the system app is both scanned and in the
2778                         * disabled packages list, then it must have been
2779                         * added via OTA. Remove it from the currently
2780                         * scanned package so the previously user-installed
2781                         * application can be scanned.
2782                         */
2783                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2784                            logCriticalInfo(Log.WARN,
2785                                    "Expecting better updated system app for " + ps.name
2786                                    + "; removing system app.  Last known"
2787                                    + " codePath=" + ps.codePathString
2788                                    + ", versionCode=" + ps.versionCode
2789                                    + "; scanned versionCode=" + scannedPkg.getLongVersionCode());
2790                            removePackageLI(scannedPkg, true);
2791                            mExpectingBetter.put(ps.name, ps.codePath);
2792                        }
2793
2794                        continue;
2795                    }
2796
2797                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2798                        psit.remove();
2799                        logCriticalInfo(Log.WARN, "System package " + ps.name
2800                                + " no longer exists; it's data will be wiped");
2801                        // Actual deletion of code and data will be handled by later
2802                        // reconciliation step
2803                    } else {
2804                        // we still have a disabled system package, but, it still might have
2805                        // been removed. check the code path still exists and check there's
2806                        // still a package. the latter can happen if an OTA keeps the same
2807                        // code path, but, changes the package name.
2808                        final PackageSetting disabledPs =
2809                                mSettings.getDisabledSystemPkgLPr(ps.name);
2810                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2811                                || disabledPs.pkg == null) {
2812                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2813                        }
2814                    }
2815                }
2816            }
2817
2818            //delete tmp files
2819            deleteTempPackageFiles();
2820
2821            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2822
2823            // Remove any shared userIDs that have no associated packages
2824            mSettings.pruneSharedUsersLPw();
2825            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2826            final int systemPackagesCount = mPackages.size();
2827            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2828                    + " ms, packageCount: " + systemPackagesCount
2829                    + " , timePerPackage: "
2830                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2831                    + " , cached: " + cachedSystemApps);
2832            if (mIsUpgrade && systemPackagesCount > 0) {
2833                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2834                        ((int) systemScanTime) / systemPackagesCount);
2835            }
2836            if (!mOnlyCore) {
2837                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2838                        SystemClock.uptimeMillis());
2839                scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2840
2841                scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags
2842                        | PackageParser.PARSE_FORWARD_LOCK,
2843                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2844
2845                // Remove disable package settings for updated system apps that were
2846                // removed via an OTA. If the update is no longer present, remove the
2847                // app completely. Otherwise, revoke their system privileges.
2848                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2849                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2850                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2851                    final String msg;
2852                    if (deletedPkg == null) {
2853                        // should have found an update, but, we didn't; remove everything
2854                        msg = "Updated system package " + deletedAppName
2855                                + " no longer exists; removing its data";
2856                        // Actual deletion of code and data will be handled by later
2857                        // reconciliation step
2858                    } else {
2859                        // found an update; revoke system privileges
2860                        msg = "Updated system package + " + deletedAppName
2861                                + " no longer exists; revoking system privileges";
2862
2863                        // Don't do anything if a stub is removed from the system image. If
2864                        // we were to remove the uncompressed version from the /data partition,
2865                        // this is where it'd be done.
2866
2867                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2868                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2869                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2870                    }
2871                    logCriticalInfo(Log.WARN, msg);
2872                }
2873
2874                /*
2875                 * Make sure all system apps that we expected to appear on
2876                 * the userdata partition actually showed up. If they never
2877                 * appeared, crawl back and revive the system version.
2878                 */
2879                for (int i = 0; i < mExpectingBetter.size(); i++) {
2880                    final String packageName = mExpectingBetter.keyAt(i);
2881                    if (!mPackages.containsKey(packageName)) {
2882                        final File scanFile = mExpectingBetter.valueAt(i);
2883
2884                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2885                                + " but never showed up; reverting to system");
2886
2887                        final @ParseFlags int reparseFlags;
2888                        final @ScanFlags int rescanFlags;
2889                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2890                            reparseFlags =
2891                                    mDefParseFlags |
2892                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2893                            rescanFlags =
2894                                    scanFlags
2895                                    | SCAN_AS_SYSTEM
2896                                    | SCAN_AS_PRIVILEGED;
2897                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2898                            reparseFlags =
2899                                    mDefParseFlags |
2900                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2901                            rescanFlags =
2902                                    scanFlags
2903                                    | SCAN_AS_SYSTEM;
2904                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)
2905                                || FileUtils.contains(privilegedOdmAppDir, scanFile)) {
2906                            reparseFlags =
2907                                    mDefParseFlags |
2908                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2909                            rescanFlags =
2910                                    scanFlags
2911                                    | SCAN_AS_SYSTEM
2912                                    | SCAN_AS_VENDOR
2913                                    | SCAN_AS_PRIVILEGED;
2914                        } else if (FileUtils.contains(vendorAppDir, scanFile)
2915                                || FileUtils.contains(odmAppDir, scanFile)) {
2916                            reparseFlags =
2917                                    mDefParseFlags |
2918                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2919                            rescanFlags =
2920                                    scanFlags
2921                                    | SCAN_AS_SYSTEM
2922                                    | SCAN_AS_VENDOR;
2923                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2924                            reparseFlags =
2925                                    mDefParseFlags |
2926                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2927                            rescanFlags =
2928                                    scanFlags
2929                                    | SCAN_AS_SYSTEM
2930                                    | SCAN_AS_OEM;
2931                        } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) {
2932                            reparseFlags =
2933                                    mDefParseFlags |
2934                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2935                            rescanFlags =
2936                                    scanFlags
2937                                    | SCAN_AS_SYSTEM
2938                                    | SCAN_AS_PRODUCT
2939                                    | SCAN_AS_PRIVILEGED;
2940                        } else if (FileUtils.contains(productAppDir, scanFile)) {
2941                            reparseFlags =
2942                                    mDefParseFlags |
2943                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2944                            rescanFlags =
2945                                    scanFlags
2946                                    | SCAN_AS_SYSTEM
2947                                    | SCAN_AS_PRODUCT;
2948                        } else {
2949                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2950                            continue;
2951                        }
2952
2953                        mSettings.enableSystemPackageLPw(packageName);
2954
2955                        try {
2956                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2957                        } catch (PackageManagerException e) {
2958                            Slog.e(TAG, "Failed to parse original system package: "
2959                                    + e.getMessage());
2960                        }
2961                    }
2962                }
2963
2964                // Uncompress and install any stubbed system applications.
2965                // This must be done last to ensure all stubs are replaced or disabled.
2966                decompressSystemApplications(stubSystemApps, scanFlags);
2967
2968                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2969                                - cachedSystemApps;
2970
2971                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2972                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2973                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2974                        + " ms, packageCount: " + dataPackagesCount
2975                        + " , timePerPackage: "
2976                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2977                        + " , cached: " + cachedNonSystemApps);
2978                if (mIsUpgrade && dataPackagesCount > 0) {
2979                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2980                            ((int) dataScanTime) / dataPackagesCount);
2981                }
2982            }
2983            mExpectingBetter.clear();
2984
2985            // Resolve the storage manager.
2986            mStorageManagerPackage = getStorageManagerPackageName();
2987
2988            // Resolve protected action filters. Only the setup wizard is allowed to
2989            // have a high priority filter for these actions.
2990            mSetupWizardPackage = getSetupWizardPackageName();
2991            if (mProtectedFilters.size() > 0) {
2992                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2993                    Slog.i(TAG, "No setup wizard;"
2994                        + " All protected intents capped to priority 0");
2995                }
2996                for (ActivityIntentInfo filter : mProtectedFilters) {
2997                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2998                        if (DEBUG_FILTERS) {
2999                            Slog.i(TAG, "Found setup wizard;"
3000                                + " allow priority " + filter.getPriority() + ";"
3001                                + " package: " + filter.activity.info.packageName
3002                                + " activity: " + filter.activity.className
3003                                + " priority: " + filter.getPriority());
3004                        }
3005                        // skip setup wizard; allow it to keep the high priority filter
3006                        continue;
3007                    }
3008                    if (DEBUG_FILTERS) {
3009                        Slog.i(TAG, "Protected action; cap priority to 0;"
3010                                + " package: " + filter.activity.info.packageName
3011                                + " activity: " + filter.activity.className
3012                                + " origPrio: " + filter.getPriority());
3013                    }
3014                    filter.setPriority(0);
3015                }
3016            }
3017
3018            mSystemTextClassifierPackage = getSystemTextClassifierPackageName();
3019
3020            mDeferProtectedFilters = false;
3021            mProtectedFilters.clear();
3022
3023            // Now that we know all of the shared libraries, update all clients to have
3024            // the correct library paths.
3025            updateAllSharedLibrariesLPw(null);
3026
3027            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
3028                // NOTE: We ignore potential failures here during a system scan (like
3029                // the rest of the commands above) because there's precious little we
3030                // can do about it. A settings error is reported, though.
3031                final List<String> changedAbiCodePath =
3032                        adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
3033                if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
3034                    for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
3035                        final String codePathString = changedAbiCodePath.get(i);
3036                        try {
3037                            mInstaller.rmdex(codePathString,
3038                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
3039                        } catch (InstallerException ignored) {
3040                        }
3041                    }
3042                }
3043                // Adjust seInfo to ensure apps which share a sharedUserId are placed in the same
3044                // SELinux domain.
3045                setting.fixSeInfoLocked();
3046            }
3047
3048            // Now that we know all the packages we are keeping,
3049            // read and update their last usage times.
3050            mPackageUsage.read(mPackages);
3051            mCompilerStats.read();
3052
3053            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
3054                    SystemClock.uptimeMillis());
3055            Slog.i(TAG, "Time to scan packages: "
3056                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
3057                    + " seconds");
3058
3059            // If the platform SDK has changed since the last time we booted,
3060            // we need to re-grant app permission to catch any new ones that
3061            // appear.  This is really a hack, and means that apps can in some
3062            // cases get permissions that the user didn't initially explicitly
3063            // allow...  it would be nice to have some better way to handle
3064            // this situation.
3065            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
3066            if (sdkUpdated) {
3067                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
3068                        + mSdkVersion + "; regranting permissions for internal storage");
3069            }
3070            mPermissionManager.updateAllPermissions(
3071                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
3072                    mPermissionCallback);
3073            ver.sdkVersion = mSdkVersion;
3074
3075            // If this is the first boot or an update from pre-M, and it is a normal
3076            // boot, then we need to initialize the default preferred apps across
3077            // all defined users.
3078            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
3079                for (UserInfo user : sUserManager.getUsers(true)) {
3080                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
3081                    applyFactoryDefaultBrowserLPw(user.id);
3082                    primeDomainVerificationsLPw(user.id);
3083                }
3084            }
3085
3086            // Prepare storage for system user really early during boot,
3087            // since core system apps like SettingsProvider and SystemUI
3088            // can't wait for user to start
3089            final int storageFlags;
3090            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3091                storageFlags = StorageManager.FLAG_STORAGE_DE;
3092            } else {
3093                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
3094            }
3095            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
3096                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
3097                    true /* onlyCoreApps */);
3098            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
3099                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
3100                        Trace.TRACE_TAG_PACKAGE_MANAGER);
3101                traceLog.traceBegin("AppDataFixup");
3102                try {
3103                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
3104                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3105                } catch (InstallerException e) {
3106                    Slog.w(TAG, "Trouble fixing GIDs", e);
3107                }
3108                traceLog.traceEnd();
3109
3110                traceLog.traceBegin("AppDataPrepare");
3111                if (deferPackages == null || deferPackages.isEmpty()) {
3112                    return;
3113                }
3114                int count = 0;
3115                for (String pkgName : deferPackages) {
3116                    PackageParser.Package pkg = null;
3117                    synchronized (mPackages) {
3118                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
3119                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
3120                            pkg = ps.pkg;
3121                        }
3122                    }
3123                    if (pkg != null) {
3124                        synchronized (mInstallLock) {
3125                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
3126                                    true /* maybeMigrateAppData */);
3127                        }
3128                        count++;
3129                    }
3130                }
3131                traceLog.traceEnd();
3132                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3133            }, "prepareAppData");
3134
3135            // If this is first boot after an OTA, and a normal boot, then
3136            // we need to clear code cache directories.
3137            // Note that we do *not* clear the application profiles. These remain valid
3138            // across OTAs and are used to drive profile verification (post OTA) and
3139            // profile compilation (without waiting to collect a fresh set of profiles).
3140            if (mIsUpgrade && !onlyCore) {
3141                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3142                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3143                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3144                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3145                        // No apps are running this early, so no need to freeze
3146                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3147                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3148                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3149                    }
3150                }
3151                ver.fingerprint = Build.FINGERPRINT;
3152            }
3153
3154            checkDefaultBrowser();
3155
3156            // clear only after permissions and other defaults have been updated
3157            mExistingSystemPackages.clear();
3158            mPromoteSystemApps = false;
3159
3160            // All the changes are done during package scanning.
3161            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3162
3163            // can downgrade to reader
3164            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3165            mSettings.writeLPr();
3166            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3167            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3168                    SystemClock.uptimeMillis());
3169
3170            if (!mOnlyCore) {
3171                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3172                mRequiredInstallerPackage = getRequiredInstallerLPr();
3173                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3174                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3175                if (mIntentFilterVerifierComponent != null) {
3176                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3177                            mIntentFilterVerifierComponent);
3178                } else {
3179                    mIntentFilterVerifier = null;
3180                }
3181                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3182                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3183                        SharedLibraryInfo.VERSION_UNDEFINED);
3184                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3185                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3186                        SharedLibraryInfo.VERSION_UNDEFINED);
3187            } else {
3188                mRequiredVerifierPackage = null;
3189                mRequiredInstallerPackage = null;
3190                mRequiredUninstallerPackage = null;
3191                mIntentFilterVerifierComponent = null;
3192                mIntentFilterVerifier = null;
3193                mServicesSystemSharedLibraryPackageName = null;
3194                mSharedSystemSharedLibraryPackageName = null;
3195            }
3196
3197            mInstallerService = new PackageInstallerService(context, this);
3198            final Pair<ComponentName, String> instantAppResolverComponent =
3199                    getInstantAppResolverLPr();
3200            if (instantAppResolverComponent != null) {
3201                if (DEBUG_INSTANT) {
3202                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3203                }
3204                mInstantAppResolverConnection = new InstantAppResolverConnection(
3205                        mContext, instantAppResolverComponent.first,
3206                        instantAppResolverComponent.second);
3207                mInstantAppResolverSettingsComponent =
3208                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3209            } else {
3210                mInstantAppResolverConnection = null;
3211                mInstantAppResolverSettingsComponent = null;
3212            }
3213            updateInstantAppInstallerLocked(null);
3214
3215            // Read and update the usage of dex files.
3216            // Do this at the end of PM init so that all the packages have their
3217            // data directory reconciled.
3218            // At this point we know the code paths of the packages, so we can validate
3219            // the disk file and build the internal cache.
3220            // The usage file is expected to be small so loading and verifying it
3221            // should take a fairly small time compare to the other activities (e.g. package
3222            // scanning).
3223            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3224            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3225            for (int userId : currentUserIds) {
3226                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3227            }
3228            mDexManager.load(userPackages);
3229            if (mIsUpgrade) {
3230                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3231                        (int) (SystemClock.uptimeMillis() - startTime));
3232            }
3233        } // synchronized (mPackages)
3234        } // synchronized (mInstallLock)
3235
3236        // Now after opening every single application zip, make sure they
3237        // are all flushed.  Not really needed, but keeps things nice and
3238        // tidy.
3239        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3240        Runtime.getRuntime().gc();
3241        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3242
3243        // The initial scanning above does many calls into installd while
3244        // holding the mPackages lock, but we're mostly interested in yelling
3245        // once we have a booted system.
3246        mInstaller.setWarnIfHeld(mPackages);
3247
3248        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3249    }
3250
3251    /**
3252     * Uncompress and install stub applications.
3253     * <p>In order to save space on the system partition, some applications are shipped in a
3254     * compressed form. In addition the compressed bits for the full application, the
3255     * system image contains a tiny stub comprised of only the Android manifest.
3256     * <p>During the first boot, attempt to uncompress and install the full application. If
3257     * the application can't be installed for any reason, disable the stub and prevent
3258     * uncompressing the full application during future boots.
3259     * <p>In order to forcefully attempt an installation of a full application, go to app
3260     * settings and enable the application.
3261     */
3262    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3263        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3264            final String pkgName = stubSystemApps.get(i);
3265            // skip if the system package is already disabled
3266            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3267                stubSystemApps.remove(i);
3268                continue;
3269            }
3270            // skip if the package isn't installed (?!); this should never happen
3271            final PackageParser.Package pkg = mPackages.get(pkgName);
3272            if (pkg == null) {
3273                stubSystemApps.remove(i);
3274                continue;
3275            }
3276            // skip if the package has been disabled by the user
3277            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3278            if (ps != null) {
3279                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3280                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3281                    stubSystemApps.remove(i);
3282                    continue;
3283                }
3284            }
3285
3286            if (DEBUG_COMPRESSION) {
3287                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3288            }
3289
3290            // uncompress the binary to its eventual destination on /data
3291            final File scanFile = decompressPackage(pkg);
3292            if (scanFile == null) {
3293                continue;
3294            }
3295
3296            // install the package to replace the stub on /system
3297            try {
3298                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3299                removePackageLI(pkg, true /*chatty*/);
3300                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3301                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3302                        UserHandle.USER_SYSTEM, "android");
3303                stubSystemApps.remove(i);
3304                continue;
3305            } catch (PackageManagerException e) {
3306                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3307            }
3308
3309            // any failed attempt to install the package will be cleaned up later
3310        }
3311
3312        // disable any stub still left; these failed to install the full application
3313        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3314            final String pkgName = stubSystemApps.get(i);
3315            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3316            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3317                    UserHandle.USER_SYSTEM, "android");
3318            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3319        }
3320    }
3321
3322    /**
3323     * Decompresses the given package on the system image onto
3324     * the /data partition.
3325     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3326     */
3327    private File decompressPackage(PackageParser.Package pkg) {
3328        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3329        if (compressedFiles == null || compressedFiles.length == 0) {
3330            if (DEBUG_COMPRESSION) {
3331                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3332            }
3333            return null;
3334        }
3335        final File dstCodePath =
3336                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3337        int ret = PackageManager.INSTALL_SUCCEEDED;
3338        try {
3339            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3340            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3341            for (File srcFile : compressedFiles) {
3342                final String srcFileName = srcFile.getName();
3343                final String dstFileName = srcFileName.substring(
3344                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3345                final File dstFile = new File(dstCodePath, dstFileName);
3346                ret = decompressFile(srcFile, dstFile);
3347                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3348                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3349                            + "; pkg: " + pkg.packageName
3350                            + ", file: " + dstFileName);
3351                    break;
3352                }
3353            }
3354        } catch (ErrnoException e) {
3355            logCriticalInfo(Log.ERROR, "Failed to decompress"
3356                    + "; pkg: " + pkg.packageName
3357                    + ", err: " + e.errno);
3358        }
3359        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3360            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3361            NativeLibraryHelper.Handle handle = null;
3362            try {
3363                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3364                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3365                        null /*abiOverride*/);
3366            } catch (IOException e) {
3367                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3368                        + "; pkg: " + pkg.packageName);
3369                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3370            } finally {
3371                IoUtils.closeQuietly(handle);
3372            }
3373        }
3374        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3375            if (dstCodePath == null || !dstCodePath.exists()) {
3376                return null;
3377            }
3378            removeCodePathLI(dstCodePath);
3379            return null;
3380        }
3381
3382        return dstCodePath;
3383    }
3384
3385    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3386        // we're only interested in updating the installer appliction when 1) it's not
3387        // already set or 2) the modified package is the installer
3388        if (mInstantAppInstallerActivity != null
3389                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3390                        .equals(modifiedPackage)) {
3391            return;
3392        }
3393        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3394    }
3395
3396    private static File preparePackageParserCache(boolean isUpgrade) {
3397        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3398            return null;
3399        }
3400
3401        // Disable package parsing on eng builds to allow for faster incremental development.
3402        if (Build.IS_ENG) {
3403            return null;
3404        }
3405
3406        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3407            Slog.i(TAG, "Disabling package parser cache due to system property.");
3408            return null;
3409        }
3410
3411        // The base directory for the package parser cache lives under /data/system/.
3412        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3413                "package_cache");
3414        if (cacheBaseDir == null) {
3415            return null;
3416        }
3417
3418        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3419        // This also serves to "GC" unused entries when the package cache version changes (which
3420        // can only happen during upgrades).
3421        if (isUpgrade) {
3422            FileUtils.deleteContents(cacheBaseDir);
3423        }
3424
3425
3426        // Return the versioned package cache directory. This is something like
3427        // "/data/system/package_cache/1"
3428        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3429
3430        if (cacheDir == null) {
3431            // Something went wrong. Attempt to delete everything and return.
3432            Slog.wtf(TAG, "Cache directory cannot be created - wiping base dir " + cacheBaseDir);
3433            FileUtils.deleteContentsAndDir(cacheBaseDir);
3434            return null;
3435        }
3436
3437        // The following is a workaround to aid development on non-numbered userdebug
3438        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3439        // the system partition is newer.
3440        //
3441        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3442        // that starts with "eng." to signify that this is an engineering build and not
3443        // destined for release.
3444        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3445            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3446
3447            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3448            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3449            // in general and should not be used for production changes. In this specific case,
3450            // we know that they will work.
3451            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3452            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3453                FileUtils.deleteContents(cacheBaseDir);
3454                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3455            }
3456        }
3457
3458        return cacheDir;
3459    }
3460
3461    @Override
3462    public boolean isFirstBoot() {
3463        // allow instant applications
3464        return mFirstBoot;
3465    }
3466
3467    @Override
3468    public boolean isOnlyCoreApps() {
3469        // allow instant applications
3470        return mOnlyCore;
3471    }
3472
3473    @Override
3474    public boolean isUpgrade() {
3475        // allow instant applications
3476        // The system property allows testing ota flow when upgraded to the same image.
3477        return mIsUpgrade || SystemProperties.getBoolean(
3478                "persist.pm.mock-upgrade", false /* default */);
3479    }
3480
3481    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3482        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3483
3484        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3485                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3486                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3487        if (matches.size() == 1) {
3488            return matches.get(0).getComponentInfo().packageName;
3489        } else if (matches.size() == 0) {
3490            Log.e(TAG, "There should probably be a verifier, but, none were found");
3491            return null;
3492        }
3493        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3494    }
3495
3496    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3497        synchronized (mPackages) {
3498            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3499            if (libraryEntry == null) {
3500                throw new IllegalStateException("Missing required shared library:" + name);
3501            }
3502            return libraryEntry.apk;
3503        }
3504    }
3505
3506    private @NonNull String getRequiredInstallerLPr() {
3507        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3508        intent.addCategory(Intent.CATEGORY_DEFAULT);
3509        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3510
3511        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3512                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3513                UserHandle.USER_SYSTEM);
3514        if (matches.size() == 1) {
3515            ResolveInfo resolveInfo = matches.get(0);
3516            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3517                throw new RuntimeException("The installer must be a privileged app");
3518            }
3519            return matches.get(0).getComponentInfo().packageName;
3520        } else {
3521            throw new RuntimeException("There must be exactly one installer; found " + matches);
3522        }
3523    }
3524
3525    private @NonNull String getRequiredUninstallerLPr() {
3526        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3527        intent.addCategory(Intent.CATEGORY_DEFAULT);
3528        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3529
3530        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3531                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3532                UserHandle.USER_SYSTEM);
3533        if (resolveInfo == null ||
3534                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3535            throw new RuntimeException("There must be exactly one uninstaller; found "
3536                    + resolveInfo);
3537        }
3538        return resolveInfo.getComponentInfo().packageName;
3539    }
3540
3541    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3542        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3543
3544        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3545                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3546                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3547        ResolveInfo best = null;
3548        final int N = matches.size();
3549        for (int i = 0; i < N; i++) {
3550            final ResolveInfo cur = matches.get(i);
3551            final String packageName = cur.getComponentInfo().packageName;
3552            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3553                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3554                continue;
3555            }
3556
3557            if (best == null || cur.priority > best.priority) {
3558                best = cur;
3559            }
3560        }
3561
3562        if (best != null) {
3563            return best.getComponentInfo().getComponentName();
3564        }
3565        Slog.w(TAG, "Intent filter verifier not found");
3566        return null;
3567    }
3568
3569    @Override
3570    public @Nullable ComponentName getInstantAppResolverComponent() {
3571        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3572            return null;
3573        }
3574        synchronized (mPackages) {
3575            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3576            if (instantAppResolver == null) {
3577                return null;
3578            }
3579            return instantAppResolver.first;
3580        }
3581    }
3582
3583    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3584        final String[] packageArray =
3585                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3586        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3587            if (DEBUG_INSTANT) {
3588                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3589            }
3590            return null;
3591        }
3592
3593        final int callingUid = Binder.getCallingUid();
3594        final int resolveFlags =
3595                MATCH_DIRECT_BOOT_AWARE
3596                | MATCH_DIRECT_BOOT_UNAWARE
3597                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3598        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3599        final Intent resolverIntent = new Intent(actionName);
3600        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3601                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3602        final int N = resolvers.size();
3603        if (N == 0) {
3604            if (DEBUG_INSTANT) {
3605                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3606            }
3607            return null;
3608        }
3609
3610        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3611        for (int i = 0; i < N; i++) {
3612            final ResolveInfo info = resolvers.get(i);
3613
3614            if (info.serviceInfo == null) {
3615                continue;
3616            }
3617
3618            final String packageName = info.serviceInfo.packageName;
3619            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3620                if (DEBUG_INSTANT) {
3621                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3622                            + " pkg: " + packageName + ", info:" + info);
3623                }
3624                continue;
3625            }
3626
3627            if (DEBUG_INSTANT) {
3628                Slog.v(TAG, "Ephemeral resolver found;"
3629                        + " pkg: " + packageName + ", info:" + info);
3630            }
3631            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3632        }
3633        if (DEBUG_INSTANT) {
3634            Slog.v(TAG, "Ephemeral resolver NOT found");
3635        }
3636        return null;
3637    }
3638
3639    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3640        String[] orderedActions = Build.IS_ENG
3641                ? new String[]{
3642                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST",
3643                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}
3644                : new String[]{
3645                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE};
3646
3647        final int resolveFlags =
3648                MATCH_DIRECT_BOOT_AWARE
3649                        | MATCH_DIRECT_BOOT_UNAWARE
3650                        | Intent.FLAG_IGNORE_EPHEMERAL
3651                        | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0);
3652        final Intent intent = new Intent();
3653        intent.addCategory(Intent.CATEGORY_DEFAULT);
3654        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3655        List<ResolveInfo> matches = null;
3656        for (String action : orderedActions) {
3657            intent.setAction(action);
3658            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3659                    resolveFlags, UserHandle.USER_SYSTEM);
3660            if (matches.isEmpty()) {
3661                if (DEBUG_INSTANT) {
3662                    Slog.d(TAG, "Instant App installer not found with " + action);
3663                }
3664            } else {
3665                break;
3666            }
3667        }
3668        Iterator<ResolveInfo> iter = matches.iterator();
3669        while (iter.hasNext()) {
3670            final ResolveInfo rInfo = iter.next();
3671            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3672            if (ps != null) {
3673                final PermissionsState permissionsState = ps.getPermissionsState();
3674                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)
3675                        || Build.IS_ENG) {
3676                    continue;
3677                }
3678            }
3679            iter.remove();
3680        }
3681        if (matches.size() == 0) {
3682            return null;
3683        } else if (matches.size() == 1) {
3684            return (ActivityInfo) matches.get(0).getComponentInfo();
3685        } else {
3686            throw new RuntimeException(
3687                    "There must be at most one ephemeral installer; found " + matches);
3688        }
3689    }
3690
3691    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3692            @NonNull ComponentName resolver) {
3693        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3694                .addCategory(Intent.CATEGORY_DEFAULT)
3695                .setPackage(resolver.getPackageName());
3696        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3697        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3698                UserHandle.USER_SYSTEM);
3699        if (matches.isEmpty()) {
3700            return null;
3701        }
3702        return matches.get(0).getComponentInfo().getComponentName();
3703    }
3704
3705    private void primeDomainVerificationsLPw(int userId) {
3706        if (DEBUG_DOMAIN_VERIFICATION) {
3707            Slog.d(TAG, "Priming domain verifications in user " + userId);
3708        }
3709
3710        SystemConfig systemConfig = SystemConfig.getInstance();
3711        ArraySet<String> packages = systemConfig.getLinkedApps();
3712
3713        for (String packageName : packages) {
3714            PackageParser.Package pkg = mPackages.get(packageName);
3715            if (pkg != null) {
3716                if (!pkg.isSystem()) {
3717                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3718                    continue;
3719                }
3720
3721                ArraySet<String> domains = null;
3722                for (PackageParser.Activity a : pkg.activities) {
3723                    for (ActivityIntentInfo filter : a.intents) {
3724                        if (hasValidDomains(filter)) {
3725                            if (domains == null) {
3726                                domains = new ArraySet<String>();
3727                            }
3728                            domains.addAll(filter.getHostsList());
3729                        }
3730                    }
3731                }
3732
3733                if (domains != null && domains.size() > 0) {
3734                    if (DEBUG_DOMAIN_VERIFICATION) {
3735                        Slog.v(TAG, "      + " + packageName);
3736                    }
3737                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3738                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3739                    // and then 'always' in the per-user state actually used for intent resolution.
3740                    final IntentFilterVerificationInfo ivi;
3741                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3742                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3743                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3744                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3745                } else {
3746                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3747                            + "' does not handle web links");
3748                }
3749            } else {
3750                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3751            }
3752        }
3753
3754        scheduleWritePackageRestrictionsLocked(userId);
3755        scheduleWriteSettingsLocked();
3756    }
3757
3758    private void applyFactoryDefaultBrowserLPw(int userId) {
3759        // The default browser app's package name is stored in a string resource,
3760        // with a product-specific overlay used for vendor customization.
3761        String browserPkg = mContext.getResources().getString(
3762                com.android.internal.R.string.default_browser);
3763        if (!TextUtils.isEmpty(browserPkg)) {
3764            // non-empty string => required to be a known package
3765            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3766            if (ps == null) {
3767                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3768                browserPkg = null;
3769            } else {
3770                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3771            }
3772        }
3773
3774        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3775        // default.  If there's more than one, just leave everything alone.
3776        if (browserPkg == null) {
3777            calculateDefaultBrowserLPw(userId);
3778        }
3779    }
3780
3781    private void calculateDefaultBrowserLPw(int userId) {
3782        List<String> allBrowsers = resolveAllBrowserApps(userId);
3783        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3784        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3785    }
3786
3787    private List<String> resolveAllBrowserApps(int userId) {
3788        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3789        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3790                PackageManager.MATCH_ALL, userId);
3791
3792        final int count = list.size();
3793        List<String> result = new ArrayList<String>(count);
3794        for (int i=0; i<count; i++) {
3795            ResolveInfo info = list.get(i);
3796            if (info.activityInfo == null
3797                    || !info.handleAllWebDataURI
3798                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3799                    || result.contains(info.activityInfo.packageName)) {
3800                continue;
3801            }
3802            result.add(info.activityInfo.packageName);
3803        }
3804
3805        return result;
3806    }
3807
3808    private boolean packageIsBrowser(String packageName, int userId) {
3809        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3810                PackageManager.MATCH_ALL, userId);
3811        final int N = list.size();
3812        for (int i = 0; i < N; i++) {
3813            ResolveInfo info = list.get(i);
3814            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3815                return true;
3816            }
3817        }
3818        return false;
3819    }
3820
3821    private void checkDefaultBrowser() {
3822        final int myUserId = UserHandle.myUserId();
3823        final String packageName = getDefaultBrowserPackageName(myUserId);
3824        if (packageName != null) {
3825            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3826            if (info == null) {
3827                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3828                synchronized (mPackages) {
3829                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3830                }
3831            }
3832        }
3833    }
3834
3835    @Override
3836    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3837            throws RemoteException {
3838        try {
3839            return super.onTransact(code, data, reply, flags);
3840        } catch (RuntimeException e) {
3841            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3842                Slog.wtf(TAG, "Package Manager Crash", e);
3843            }
3844            throw e;
3845        }
3846    }
3847
3848    static int[] appendInts(int[] cur, int[] add) {
3849        if (add == null) return cur;
3850        if (cur == null) return add;
3851        final int N = add.length;
3852        for (int i=0; i<N; i++) {
3853            cur = appendInt(cur, add[i]);
3854        }
3855        return cur;
3856    }
3857
3858    /**
3859     * Returns whether or not a full application can see an instant application.
3860     * <p>
3861     * Currently, there are three cases in which this can occur:
3862     * <ol>
3863     * <li>The calling application is a "special" process. Special processes
3864     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3865     * <li>The calling application has the permission
3866     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3867     * <li>The calling application is the default launcher on the
3868     *     system partition.</li>
3869     * </ol>
3870     */
3871    private boolean canViewInstantApps(int callingUid, int userId) {
3872        if (callingUid < Process.FIRST_APPLICATION_UID) {
3873            return true;
3874        }
3875        if (mContext.checkCallingOrSelfPermission(
3876                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3877            return true;
3878        }
3879        if (mContext.checkCallingOrSelfPermission(
3880                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3881            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3882            if (homeComponent != null
3883                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3884                return true;
3885            }
3886        }
3887        return false;
3888    }
3889
3890    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3891        if (!sUserManager.exists(userId)) return null;
3892        if (ps == null) {
3893            return null;
3894        }
3895        final int callingUid = Binder.getCallingUid();
3896        // Filter out ephemeral app metadata:
3897        //   * The system/shell/root can see metadata for any app
3898        //   * An installed app can see metadata for 1) other installed apps
3899        //     and 2) ephemeral apps that have explicitly interacted with it
3900        //   * Ephemeral apps can only see their own data and exposed installed apps
3901        //   * Holding a signature permission allows seeing instant apps
3902        if (filterAppAccessLPr(ps, callingUid, userId)) {
3903            return null;
3904        }
3905
3906        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3907                && ps.isSystem()) {
3908            flags |= MATCH_ANY_USER;
3909        }
3910
3911        final PackageUserState state = ps.readUserState(userId);
3912        PackageParser.Package p = ps.pkg;
3913        if (p != null) {
3914            final PermissionsState permissionsState = ps.getPermissionsState();
3915
3916            // Compute GIDs only if requested
3917            final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3918                    ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3919            // Compute granted permissions only if package has requested permissions
3920            final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3921                    ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3922
3923            PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3924                    ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3925
3926            if (packageInfo == null) {
3927                return null;
3928            }
3929
3930            packageInfo.packageName = packageInfo.applicationInfo.packageName =
3931                    resolveExternalPackageNameLPr(p);
3932
3933            return packageInfo;
3934        } else if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 && state.isAvailable(flags)) {
3935            PackageInfo pi = new PackageInfo();
3936            pi.packageName = ps.name;
3937            pi.setLongVersionCode(ps.versionCode);
3938            pi.sharedUserId = (ps.sharedUser != null) ? ps.sharedUser.name : null;
3939            pi.firstInstallTime = ps.firstInstallTime;
3940            pi.lastUpdateTime = ps.lastUpdateTime;
3941
3942            ApplicationInfo ai = new ApplicationInfo();
3943            ai.packageName = ps.name;
3944            ai.uid = UserHandle.getUid(userId, ps.appId);
3945            ai.primaryCpuAbi = ps.primaryCpuAbiString;
3946            ai.secondaryCpuAbi = ps.secondaryCpuAbiString;
3947            ai.setVersionCode(ps.versionCode);
3948            ai.flags = ps.pkgFlags;
3949            ai.privateFlags = ps.pkgPrivateFlags;
3950            pi.applicationInfo = PackageParser.generateApplicationInfo(ai, flags, state, userId);
3951
3952            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "ps.pkg is n/a for ["
3953                    + ps.name + "]. Provides a minimum info.");
3954            return pi;
3955        } else {
3956            return null;
3957        }
3958    }
3959
3960    @Override
3961    public void checkPackageStartable(String packageName, int userId) {
3962        final int callingUid = Binder.getCallingUid();
3963        if (getInstantAppPackageName(callingUid) != null) {
3964            throw new SecurityException("Instant applications don't have access to this method");
3965        }
3966        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3967        synchronized (mPackages) {
3968            final PackageSetting ps = mSettings.mPackages.get(packageName);
3969            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3970                throw new SecurityException("Package " + packageName + " was not found!");
3971            }
3972
3973            if (!ps.getInstalled(userId)) {
3974                throw new SecurityException(
3975                        "Package " + packageName + " was not installed for user " + userId + "!");
3976            }
3977
3978            if (mSafeMode && !ps.isSystem()) {
3979                throw new SecurityException("Package " + packageName + " not a system app!");
3980            }
3981
3982            if (mFrozenPackages.contains(packageName)) {
3983                throw new SecurityException("Package " + packageName + " is currently frozen!");
3984            }
3985
3986            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3987                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3988            }
3989        }
3990    }
3991
3992    @Override
3993    public boolean isPackageAvailable(String packageName, int userId) {
3994        if (!sUserManager.exists(userId)) return false;
3995        final int callingUid = Binder.getCallingUid();
3996        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3997                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3998        synchronized (mPackages) {
3999            PackageParser.Package p = mPackages.get(packageName);
4000            if (p != null) {
4001                final PackageSetting ps = (PackageSetting) p.mExtras;
4002                if (filterAppAccessLPr(ps, callingUid, userId)) {
4003                    return false;
4004                }
4005                if (ps != null) {
4006                    final PackageUserState state = ps.readUserState(userId);
4007                    if (state != null) {
4008                        return PackageParser.isAvailable(state);
4009                    }
4010                }
4011            }
4012        }
4013        return false;
4014    }
4015
4016    @Override
4017    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
4018        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
4019                flags, Binder.getCallingUid(), userId);
4020    }
4021
4022    @Override
4023    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
4024            int flags, int userId) {
4025        return getPackageInfoInternal(versionedPackage.getPackageName(),
4026                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
4027    }
4028
4029    /**
4030     * Important: The provided filterCallingUid is used exclusively to filter out packages
4031     * that can be seen based on user state. It's typically the original caller uid prior
4032     * to clearing. Because it can only be provided by trusted code, it's value can be
4033     * trusted and will be used as-is; unlike userId which will be validated by this method.
4034     */
4035    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
4036            int flags, int filterCallingUid, int userId) {
4037        if (!sUserManager.exists(userId)) return null;
4038        flags = updateFlagsForPackage(flags, userId, packageName);
4039        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4040                false /* requireFullPermission */, false /* checkShell */, "get package info");
4041
4042        // reader
4043        synchronized (mPackages) {
4044            // Normalize package name to handle renamed packages and static libs
4045            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
4046
4047            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
4048            if (matchFactoryOnly) {
4049                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
4050                if (ps != null) {
4051                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4052                        return null;
4053                    }
4054                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4055                        return null;
4056                    }
4057                    return generatePackageInfo(ps, flags, userId);
4058                }
4059            }
4060
4061            PackageParser.Package p = mPackages.get(packageName);
4062            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
4063                return null;
4064            }
4065            if (DEBUG_PACKAGE_INFO)
4066                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
4067            if (p != null) {
4068                final PackageSetting ps = (PackageSetting) p.mExtras;
4069                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4070                    return null;
4071                }
4072                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
4073                    return null;
4074                }
4075                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4076            }
4077            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4078                final PackageSetting ps = mSettings.mPackages.get(packageName);
4079                if (ps == null) return null;
4080                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4081                    return null;
4082                }
4083                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4084                    return null;
4085                }
4086                return generatePackageInfo(ps, flags, userId);
4087            }
4088        }
4089        return null;
4090    }
4091
4092    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4093        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4094            return true;
4095        }
4096        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4097            return true;
4098        }
4099        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4100            return true;
4101        }
4102        return false;
4103    }
4104
4105    private boolean isComponentVisibleToInstantApp(
4106            @Nullable ComponentName component, @ComponentType int type) {
4107        if (type == TYPE_ACTIVITY) {
4108            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4109            if (activity == null) {
4110                return false;
4111            }
4112            final boolean visibleToInstantApp =
4113                    (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4114            final boolean explicitlyVisibleToInstantApp =
4115                    (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
4116            return visibleToInstantApp && explicitlyVisibleToInstantApp;
4117        } else if (type == TYPE_RECEIVER) {
4118            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4119            if (activity == null) {
4120                return false;
4121            }
4122            final boolean visibleToInstantApp =
4123                    (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4124            final boolean explicitlyVisibleToInstantApp =
4125                    (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
4126            return visibleToInstantApp && !explicitlyVisibleToInstantApp;
4127        } else if (type == TYPE_SERVICE) {
4128            final PackageParser.Service service = mServices.mServices.get(component);
4129            return service != null
4130                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4131                    : false;
4132        } else if (type == TYPE_PROVIDER) {
4133            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4134            return provider != null
4135                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4136                    : false;
4137        } else if (type == TYPE_UNKNOWN) {
4138            return isComponentVisibleToInstantApp(component);
4139        }
4140        return false;
4141    }
4142
4143    /**
4144     * Returns whether or not access to the application should be filtered.
4145     * <p>
4146     * Access may be limited based upon whether the calling or target applications
4147     * are instant applications.
4148     *
4149     * @see #canAccessInstantApps(int)
4150     */
4151    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4152            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4153        // if we're in an isolated process, get the real calling UID
4154        if (Process.isIsolated(callingUid)) {
4155            callingUid = mIsolatedOwners.get(callingUid);
4156        }
4157        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4158        final boolean callerIsInstantApp = instantAppPkgName != null;
4159        if (ps == null) {
4160            if (callerIsInstantApp) {
4161                // pretend the application exists, but, needs to be filtered
4162                return true;
4163            }
4164            return false;
4165        }
4166        // if the target and caller are the same application, don't filter
4167        if (isCallerSameApp(ps.name, callingUid)) {
4168            return false;
4169        }
4170        if (callerIsInstantApp) {
4171            // both caller and target are both instant, but, different applications, filter
4172            if (ps.getInstantApp(userId)) {
4173                return true;
4174            }
4175            // request for a specific component; if it hasn't been explicitly exposed through
4176            // property or instrumentation target, filter
4177            if (component != null) {
4178                final PackageParser.Instrumentation instrumentation =
4179                        mInstrumentation.get(component);
4180                if (instrumentation != null
4181                        && isCallerSameApp(instrumentation.info.targetPackage, callingUid)) {
4182                    return false;
4183                }
4184                return !isComponentVisibleToInstantApp(component, componentType);
4185            }
4186            // request for application; if no components have been explicitly exposed, filter
4187            return !ps.pkg.visibleToInstantApps;
4188        }
4189        if (ps.getInstantApp(userId)) {
4190            // caller can see all components of all instant applications, don't filter
4191            if (canViewInstantApps(callingUid, userId)) {
4192                return false;
4193            }
4194            // request for a specific instant application component, filter
4195            if (component != null) {
4196                return true;
4197            }
4198            // request for an instant application; if the caller hasn't been granted access, filter
4199            return !mInstantAppRegistry.isInstantAccessGranted(
4200                    userId, UserHandle.getAppId(callingUid), ps.appId);
4201        }
4202        return false;
4203    }
4204
4205    /**
4206     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4207     */
4208    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4209        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4210    }
4211
4212    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4213            int flags) {
4214        // Callers can access only the libs they depend on, otherwise they need to explicitly
4215        // ask for the shared libraries given the caller is allowed to access all static libs.
4216        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4217            // System/shell/root get to see all static libs
4218            final int appId = UserHandle.getAppId(uid);
4219            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4220                    || appId == Process.ROOT_UID) {
4221                return false;
4222            }
4223            // Installer gets to see all static libs.
4224            if (PackageManager.PERMISSION_GRANTED
4225                    == checkUidPermission(Manifest.permission.INSTALL_PACKAGES, uid)) {
4226                return false;
4227            }
4228        }
4229
4230        // No package means no static lib as it is always on internal storage
4231        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4232            return false;
4233        }
4234
4235        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4236                ps.pkg.staticSharedLibVersion);
4237        if (libEntry == null) {
4238            return false;
4239        }
4240
4241        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4242        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4243        if (uidPackageNames == null) {
4244            return true;
4245        }
4246
4247        for (String uidPackageName : uidPackageNames) {
4248            if (ps.name.equals(uidPackageName)) {
4249                return false;
4250            }
4251            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4252            if (uidPs != null) {
4253                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4254                        libEntry.info.getName());
4255                if (index < 0) {
4256                    continue;
4257                }
4258                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4259                    return false;
4260                }
4261            }
4262        }
4263        return true;
4264    }
4265
4266    @Override
4267    public String[] currentToCanonicalPackageNames(String[] names) {
4268        final int callingUid = Binder.getCallingUid();
4269        if (getInstantAppPackageName(callingUid) != null) {
4270            return names;
4271        }
4272        final String[] out = new String[names.length];
4273        // reader
4274        synchronized (mPackages) {
4275            final int callingUserId = UserHandle.getUserId(callingUid);
4276            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4277            for (int i=names.length-1; i>=0; i--) {
4278                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4279                boolean translateName = false;
4280                if (ps != null && ps.realName != null) {
4281                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4282                    translateName = !targetIsInstantApp
4283                            || canViewInstantApps
4284                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4285                                    UserHandle.getAppId(callingUid), ps.appId);
4286                }
4287                out[i] = translateName ? ps.realName : names[i];
4288            }
4289        }
4290        return out;
4291    }
4292
4293    @Override
4294    public String[] canonicalToCurrentPackageNames(String[] names) {
4295        final int callingUid = Binder.getCallingUid();
4296        if (getInstantAppPackageName(callingUid) != null) {
4297            return names;
4298        }
4299        final String[] out = new String[names.length];
4300        // reader
4301        synchronized (mPackages) {
4302            final int callingUserId = UserHandle.getUserId(callingUid);
4303            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4304            for (int i=names.length-1; i>=0; i--) {
4305                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4306                boolean translateName = false;
4307                if (cur != null) {
4308                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4309                    final boolean targetIsInstantApp =
4310                            ps != null && ps.getInstantApp(callingUserId);
4311                    translateName = !targetIsInstantApp
4312                            || canViewInstantApps
4313                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4314                                    UserHandle.getAppId(callingUid), ps.appId);
4315                }
4316                out[i] = translateName ? cur : names[i];
4317            }
4318        }
4319        return out;
4320    }
4321
4322    @Override
4323    public int getPackageUid(String packageName, int flags, int userId) {
4324        if (!sUserManager.exists(userId)) return -1;
4325        final int callingUid = Binder.getCallingUid();
4326        flags = updateFlagsForPackage(flags, userId, packageName);
4327        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4328                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4329
4330        // reader
4331        synchronized (mPackages) {
4332            final PackageParser.Package p = mPackages.get(packageName);
4333            if (p != null && p.isMatch(flags)) {
4334                PackageSetting ps = (PackageSetting) p.mExtras;
4335                if (filterAppAccessLPr(ps, callingUid, userId)) {
4336                    return -1;
4337                }
4338                return UserHandle.getUid(userId, p.applicationInfo.uid);
4339            }
4340            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4341                final PackageSetting ps = mSettings.mPackages.get(packageName);
4342                if (ps != null && ps.isMatch(flags)
4343                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4344                    return UserHandle.getUid(userId, ps.appId);
4345                }
4346            }
4347        }
4348
4349        return -1;
4350    }
4351
4352    @Override
4353    public int[] getPackageGids(String packageName, int flags, int userId) {
4354        if (!sUserManager.exists(userId)) return null;
4355        final int callingUid = Binder.getCallingUid();
4356        flags = updateFlagsForPackage(flags, userId, packageName);
4357        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4358                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4359
4360        // reader
4361        synchronized (mPackages) {
4362            final PackageParser.Package p = mPackages.get(packageName);
4363            if (p != null && p.isMatch(flags)) {
4364                PackageSetting ps = (PackageSetting) p.mExtras;
4365                if (filterAppAccessLPr(ps, callingUid, userId)) {
4366                    return null;
4367                }
4368                // TODO: Shouldn't this be checking for package installed state for userId and
4369                // return null?
4370                return ps.getPermissionsState().computeGids(userId);
4371            }
4372            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4373                final PackageSetting ps = mSettings.mPackages.get(packageName);
4374                if (ps != null && ps.isMatch(flags)
4375                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4376                    return ps.getPermissionsState().computeGids(userId);
4377                }
4378            }
4379        }
4380
4381        return null;
4382    }
4383
4384    @Override
4385    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4386        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4387    }
4388
4389    @Override
4390    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4391            int flags) {
4392        final List<PermissionInfo> permissionList =
4393                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4394        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4395    }
4396
4397    @Override
4398    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4399        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4400    }
4401
4402    @Override
4403    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4404        final List<PermissionGroupInfo> permissionList =
4405                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4406        return (permissionList == null)
4407                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4408    }
4409
4410    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4411            int filterCallingUid, int userId) {
4412        if (!sUserManager.exists(userId)) return null;
4413        PackageSetting ps = mSettings.mPackages.get(packageName);
4414        if (ps != null) {
4415            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4416                return null;
4417            }
4418            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4419                return null;
4420            }
4421            if (ps.pkg == null) {
4422                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4423                if (pInfo != null) {
4424                    return pInfo.applicationInfo;
4425                }
4426                return null;
4427            }
4428            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4429                    ps.readUserState(userId), userId);
4430            if (ai != null) {
4431                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4432            }
4433            return ai;
4434        }
4435        return null;
4436    }
4437
4438    @Override
4439    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4440        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4441    }
4442
4443    /**
4444     * Important: The provided filterCallingUid is used exclusively to filter out applications
4445     * that can be seen based on user state. It's typically the original caller uid prior
4446     * to clearing. Because it can only be provided by trusted code, it's value can be
4447     * trusted and will be used as-is; unlike userId which will be validated by this method.
4448     */
4449    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4450            int filterCallingUid, int userId) {
4451        if (!sUserManager.exists(userId)) return null;
4452        flags = updateFlagsForApplication(flags, userId, packageName);
4453        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4454                false /* requireFullPermission */, false /* checkShell */, "get application info");
4455
4456        // writer
4457        synchronized (mPackages) {
4458            // Normalize package name to handle renamed packages and static libs
4459            packageName = resolveInternalPackageNameLPr(packageName,
4460                    PackageManager.VERSION_CODE_HIGHEST);
4461
4462            PackageParser.Package p = mPackages.get(packageName);
4463            if (DEBUG_PACKAGE_INFO) Log.v(
4464                    TAG, "getApplicationInfo " + packageName
4465                    + ": " + p);
4466            if (p != null) {
4467                PackageSetting ps = mSettings.mPackages.get(packageName);
4468                if (ps == null) return null;
4469                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4470                    return null;
4471                }
4472                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4473                    return null;
4474                }
4475                // Note: isEnabledLP() does not apply here - always return info
4476                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4477                        p, flags, ps.readUserState(userId), userId);
4478                if (ai != null) {
4479                    ai.packageName = resolveExternalPackageNameLPr(p);
4480                }
4481                return ai;
4482            }
4483            if ("android".equals(packageName)||"system".equals(packageName)) {
4484                return mAndroidApplication;
4485            }
4486            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4487                // Already generates the external package name
4488                return generateApplicationInfoFromSettingsLPw(packageName,
4489                        flags, filterCallingUid, userId);
4490            }
4491        }
4492        return null;
4493    }
4494
4495    private String normalizePackageNameLPr(String packageName) {
4496        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4497        return normalizedPackageName != null ? normalizedPackageName : packageName;
4498    }
4499
4500    @Override
4501    public void deletePreloadsFileCache() {
4502        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4503            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4504        }
4505        File dir = Environment.getDataPreloadsFileCacheDirectory();
4506        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4507        FileUtils.deleteContents(dir);
4508    }
4509
4510    @Override
4511    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4512            final int storageFlags, final IPackageDataObserver observer) {
4513        mContext.enforceCallingOrSelfPermission(
4514                android.Manifest.permission.CLEAR_APP_CACHE, null);
4515        mHandler.post(() -> {
4516            boolean success = false;
4517            try {
4518                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4519                success = true;
4520            } catch (IOException e) {
4521                Slog.w(TAG, e);
4522            }
4523            if (observer != null) {
4524                try {
4525                    observer.onRemoveCompleted(null, success);
4526                } catch (RemoteException e) {
4527                    Slog.w(TAG, e);
4528                }
4529            }
4530        });
4531    }
4532
4533    @Override
4534    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4535            final int storageFlags, final IntentSender pi) {
4536        mContext.enforceCallingOrSelfPermission(
4537                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4538        mHandler.post(() -> {
4539            boolean success = false;
4540            try {
4541                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4542                success = true;
4543            } catch (IOException e) {
4544                Slog.w(TAG, e);
4545            }
4546            if (pi != null) {
4547                try {
4548                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4549                } catch (SendIntentException e) {
4550                    Slog.w(TAG, e);
4551                }
4552            }
4553        });
4554    }
4555
4556    /**
4557     * Blocking call to clear various types of cached data across the system
4558     * until the requested bytes are available.
4559     */
4560    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4561        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4562        final File file = storage.findPathForUuid(volumeUuid);
4563        if (file.getUsableSpace() >= bytes) return;
4564
4565        if (ENABLE_FREE_CACHE_V2) {
4566            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4567                    volumeUuid);
4568            final boolean aggressive = (storageFlags
4569                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4570            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4571
4572            // 1. Pre-flight to determine if we have any chance to succeed
4573            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4574            if (internalVolume && (aggressive || SystemProperties
4575                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4576                deletePreloadsFileCache();
4577                if (file.getUsableSpace() >= bytes) return;
4578            }
4579
4580            // 3. Consider parsed APK data (aggressive only)
4581            if (internalVolume && aggressive) {
4582                FileUtils.deleteContents(mCacheDir);
4583                if (file.getUsableSpace() >= bytes) return;
4584            }
4585
4586            // 4. Consider cached app data (above quotas)
4587            try {
4588                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4589                        Installer.FLAG_FREE_CACHE_V2);
4590            } catch (InstallerException ignored) {
4591            }
4592            if (file.getUsableSpace() >= bytes) return;
4593
4594            // 5. Consider shared libraries with refcount=0 and age>min cache period
4595            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4596                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4597                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4598                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4599                return;
4600            }
4601
4602            // 6. Consider dexopt output (aggressive only)
4603            // TODO: Implement
4604
4605            // 7. Consider installed instant apps unused longer than min cache period
4606            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4607                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4608                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4609                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4610                return;
4611            }
4612
4613            // 8. Consider cached app data (below quotas)
4614            try {
4615                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4616                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4617            } catch (InstallerException ignored) {
4618            }
4619            if (file.getUsableSpace() >= bytes) return;
4620
4621            // 9. Consider DropBox entries
4622            // TODO: Implement
4623
4624            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4625            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4626                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4627                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4628                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4629                return;
4630            }
4631        } else {
4632            try {
4633                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4634            } catch (InstallerException ignored) {
4635            }
4636            if (file.getUsableSpace() >= bytes) return;
4637        }
4638
4639        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4640    }
4641
4642    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4643            throws IOException {
4644        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4645        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4646
4647        List<VersionedPackage> packagesToDelete = null;
4648        final long now = System.currentTimeMillis();
4649
4650        synchronized (mPackages) {
4651            final int[] allUsers = sUserManager.getUserIds();
4652            final int libCount = mSharedLibraries.size();
4653            for (int i = 0; i < libCount; i++) {
4654                final LongSparseArray<SharedLibraryEntry> versionedLib
4655                        = mSharedLibraries.valueAt(i);
4656                if (versionedLib == null) {
4657                    continue;
4658                }
4659                final int versionCount = versionedLib.size();
4660                for (int j = 0; j < versionCount; j++) {
4661                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4662                    // Skip packages that are not static shared libs.
4663                    if (!libInfo.isStatic()) {
4664                        break;
4665                    }
4666                    // Important: We skip static shared libs used for some user since
4667                    // in such a case we need to keep the APK on the device. The check for
4668                    // a lib being used for any user is performed by the uninstall call.
4669                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4670                    // Resolve the package name - we use synthetic package names internally
4671                    final String internalPackageName = resolveInternalPackageNameLPr(
4672                            declaringPackage.getPackageName(),
4673                            declaringPackage.getLongVersionCode());
4674                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4675                    // Skip unused static shared libs cached less than the min period
4676                    // to prevent pruning a lib needed by a subsequently installed package.
4677                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4678                        continue;
4679                    }
4680                    if (packagesToDelete == null) {
4681                        packagesToDelete = new ArrayList<>();
4682                    }
4683                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4684                            declaringPackage.getLongVersionCode()));
4685                }
4686            }
4687        }
4688
4689        if (packagesToDelete != null) {
4690            final int packageCount = packagesToDelete.size();
4691            for (int i = 0; i < packageCount; i++) {
4692                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4693                // Delete the package synchronously (will fail of the lib used for any user).
4694                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4695                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4696                                == PackageManager.DELETE_SUCCEEDED) {
4697                    if (volume.getUsableSpace() >= neededSpace) {
4698                        return true;
4699                    }
4700                }
4701            }
4702        }
4703
4704        return false;
4705    }
4706
4707    /**
4708     * Update given flags based on encryption status of current user.
4709     */
4710    private int updateFlags(int flags, int userId) {
4711        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4712                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4713            // Caller expressed an explicit opinion about what encryption
4714            // aware/unaware components they want to see, so fall through and
4715            // give them what they want
4716        } else {
4717            // Caller expressed no opinion, so match based on user state
4718            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4719                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4720            } else {
4721                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4722            }
4723        }
4724        return flags;
4725    }
4726
4727    private UserManagerInternal getUserManagerInternal() {
4728        if (mUserManagerInternal == null) {
4729            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4730        }
4731        return mUserManagerInternal;
4732    }
4733
4734    private ActivityManagerInternal getActivityManagerInternal() {
4735        if (mActivityManagerInternal == null) {
4736            mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
4737        }
4738        return mActivityManagerInternal;
4739    }
4740
4741
4742    private DeviceIdleController.LocalService getDeviceIdleController() {
4743        if (mDeviceIdleController == null) {
4744            mDeviceIdleController =
4745                    LocalServices.getService(DeviceIdleController.LocalService.class);
4746        }
4747        return mDeviceIdleController;
4748    }
4749
4750    /**
4751     * Update given flags when being used to request {@link PackageInfo}.
4752     */
4753    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4754        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4755        boolean triaged = true;
4756        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4757                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4758            // Caller is asking for component details, so they'd better be
4759            // asking for specific encryption matching behavior, or be triaged
4760            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4761                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4762                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4763                triaged = false;
4764            }
4765        }
4766        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4767                | PackageManager.MATCH_SYSTEM_ONLY
4768                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4769            triaged = false;
4770        }
4771        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4772            mPermissionManager.enforceCrossUserPermission(
4773                    Binder.getCallingUid(), userId, false, false,
4774                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4775                    + Debug.getCallers(5));
4776        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4777                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4778            // If the caller wants all packages and has a restricted profile associated with it,
4779            // then match all users. This is to make sure that launchers that need to access work
4780            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4781            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4782            flags |= PackageManager.MATCH_ANY_USER;
4783        }
4784        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4785            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4786                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4787        }
4788        return updateFlags(flags, userId);
4789    }
4790
4791    /**
4792     * Update given flags when being used to request {@link ApplicationInfo}.
4793     */
4794    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4795        return updateFlagsForPackage(flags, userId, cookie);
4796    }
4797
4798    /**
4799     * Update given flags when being used to request {@link ComponentInfo}.
4800     */
4801    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4802        if (cookie instanceof Intent) {
4803            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4804                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4805            }
4806        }
4807
4808        boolean triaged = true;
4809        // Caller is asking for component details, so they'd better be
4810        // asking for specific encryption matching behavior, or be triaged
4811        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4812                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4813                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4814            triaged = false;
4815        }
4816        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4817            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4818                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4819        }
4820
4821        return updateFlags(flags, userId);
4822    }
4823
4824    /**
4825     * Update given intent when being used to request {@link ResolveInfo}.
4826     */
4827    private Intent updateIntentForResolve(Intent intent) {
4828        if (intent.getSelector() != null) {
4829            intent = intent.getSelector();
4830        }
4831        if (DEBUG_PREFERRED) {
4832            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4833        }
4834        return intent;
4835    }
4836
4837    /**
4838     * Update given flags when being used to request {@link ResolveInfo}.
4839     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4840     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4841     * flag set. However, this flag is only honoured in three circumstances:
4842     * <ul>
4843     * <li>when called from a system process</li>
4844     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4845     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4846     * action and a {@code android.intent.category.BROWSABLE} category</li>
4847     * </ul>
4848     */
4849    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4850        return updateFlagsForResolve(flags, userId, intent, callingUid,
4851                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4852    }
4853    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4854            boolean wantInstantApps) {
4855        return updateFlagsForResolve(flags, userId, intent, callingUid,
4856                wantInstantApps, false /*onlyExposedExplicitly*/);
4857    }
4858    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4859            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4860        // Safe mode means we shouldn't match any third-party components
4861        if (mSafeMode) {
4862            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4863        }
4864        if (getInstantAppPackageName(callingUid) != null) {
4865            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4866            if (onlyExposedExplicitly) {
4867                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4868            }
4869            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4870            flags |= PackageManager.MATCH_INSTANT;
4871        } else {
4872            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4873            final boolean allowMatchInstant = wantInstantApps
4874                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4875            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4876                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4877            if (!allowMatchInstant) {
4878                flags &= ~PackageManager.MATCH_INSTANT;
4879            }
4880        }
4881        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4882    }
4883
4884    @Override
4885    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4886        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4887    }
4888
4889    /**
4890     * Important: The provided filterCallingUid is used exclusively to filter out activities
4891     * that can be seen based on user state. It's typically the original caller uid prior
4892     * to clearing. Because it can only be provided by trusted code, it's value can be
4893     * trusted and will be used as-is; unlike userId which will be validated by this method.
4894     */
4895    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4896            int filterCallingUid, int userId) {
4897        if (!sUserManager.exists(userId)) return null;
4898        flags = updateFlagsForComponent(flags, userId, component);
4899
4900        if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) {
4901            mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4902                    false /* requireFullPermission */, false /* checkShell */, "get activity info");
4903        }
4904
4905        synchronized (mPackages) {
4906            PackageParser.Activity a = mActivities.mActivities.get(component);
4907
4908            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4909            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4910                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4911                if (ps == null) return null;
4912                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4913                    return null;
4914                }
4915                return PackageParser.generateActivityInfo(
4916                        a, flags, ps.readUserState(userId), userId);
4917            }
4918            if (mResolveComponentName.equals(component)) {
4919                return PackageParser.generateActivityInfo(
4920                        mResolveActivity, flags, new PackageUserState(), userId);
4921            }
4922        }
4923        return null;
4924    }
4925
4926    private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) {
4927        if (!getActivityManagerInternal().isCallerRecents(callingUid)) {
4928            return false;
4929        }
4930        final long token = Binder.clearCallingIdentity();
4931        try {
4932            final int callingUserId = UserHandle.getUserId(callingUid);
4933            if (ActivityManager.getCurrentUser() != callingUserId) {
4934                return false;
4935            }
4936            return sUserManager.isSameProfileGroup(callingUserId, targetUserId);
4937        } finally {
4938            Binder.restoreCallingIdentity(token);
4939        }
4940    }
4941
4942    @Override
4943    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4944            String resolvedType) {
4945        synchronized (mPackages) {
4946            if (component.equals(mResolveComponentName)) {
4947                // The resolver supports EVERYTHING!
4948                return true;
4949            }
4950            final int callingUid = Binder.getCallingUid();
4951            final int callingUserId = UserHandle.getUserId(callingUid);
4952            PackageParser.Activity a = mActivities.mActivities.get(component);
4953            if (a == null) {
4954                return false;
4955            }
4956            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4957            if (ps == null) {
4958                return false;
4959            }
4960            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4961                return false;
4962            }
4963            for (int i=0; i<a.intents.size(); i++) {
4964                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4965                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4966                    return true;
4967                }
4968            }
4969            return false;
4970        }
4971    }
4972
4973    @Override
4974    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4975        if (!sUserManager.exists(userId)) return null;
4976        final int callingUid = Binder.getCallingUid();
4977        flags = updateFlagsForComponent(flags, userId, component);
4978        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4979                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4980        synchronized (mPackages) {
4981            PackageParser.Activity a = mReceivers.mActivities.get(component);
4982            if (DEBUG_PACKAGE_INFO) Log.v(
4983                TAG, "getReceiverInfo " + component + ": " + a);
4984            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4985                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4986                if (ps == null) return null;
4987                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4988                    return null;
4989                }
4990                return PackageParser.generateActivityInfo(
4991                        a, flags, ps.readUserState(userId), userId);
4992            }
4993        }
4994        return null;
4995    }
4996
4997    @Override
4998    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4999            int flags, int userId) {
5000        if (!sUserManager.exists(userId)) return null;
5001        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
5002        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5003            return null;
5004        }
5005
5006        flags = updateFlagsForPackage(flags, userId, null);
5007
5008        final boolean canSeeStaticLibraries =
5009                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
5010                        == PERMISSION_GRANTED
5011                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
5012                        == PERMISSION_GRANTED
5013                || canRequestPackageInstallsInternal(packageName,
5014                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
5015                        false  /* throwIfPermNotDeclared*/)
5016                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
5017                        == PERMISSION_GRANTED;
5018
5019        synchronized (mPackages) {
5020            List<SharedLibraryInfo> result = null;
5021
5022            final int libCount = mSharedLibraries.size();
5023            for (int i = 0; i < libCount; i++) {
5024                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5025                if (versionedLib == null) {
5026                    continue;
5027                }
5028
5029                final int versionCount = versionedLib.size();
5030                for (int j = 0; j < versionCount; j++) {
5031                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
5032                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
5033                        break;
5034                    }
5035                    final long identity = Binder.clearCallingIdentity();
5036                    try {
5037                        PackageInfo packageInfo = getPackageInfoVersioned(
5038                                libInfo.getDeclaringPackage(), flags
5039                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
5040                        if (packageInfo == null) {
5041                            continue;
5042                        }
5043                    } finally {
5044                        Binder.restoreCallingIdentity(identity);
5045                    }
5046
5047                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
5048                            libInfo.getLongVersion(), libInfo.getType(),
5049                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
5050                            flags, userId));
5051
5052                    if (result == null) {
5053                        result = new ArrayList<>();
5054                    }
5055                    result.add(resLibInfo);
5056                }
5057            }
5058
5059            return result != null ? new ParceledListSlice<>(result) : null;
5060        }
5061    }
5062
5063    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
5064            SharedLibraryInfo libInfo, int flags, int userId) {
5065        List<VersionedPackage> versionedPackages = null;
5066        final int packageCount = mSettings.mPackages.size();
5067        for (int i = 0; i < packageCount; i++) {
5068            PackageSetting ps = mSettings.mPackages.valueAt(i);
5069
5070            if (ps == null) {
5071                continue;
5072            }
5073
5074            if (!ps.getUserState().get(userId).isAvailable(flags)) {
5075                continue;
5076            }
5077
5078            final String libName = libInfo.getName();
5079            if (libInfo.isStatic()) {
5080                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5081                if (libIdx < 0) {
5082                    continue;
5083                }
5084                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
5085                    continue;
5086                }
5087                if (versionedPackages == null) {
5088                    versionedPackages = new ArrayList<>();
5089                }
5090                // If the dependent is a static shared lib, use the public package name
5091                String dependentPackageName = ps.name;
5092                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5093                    dependentPackageName = ps.pkg.manifestPackageName;
5094                }
5095                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5096            } else if (ps.pkg != null) {
5097                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5098                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5099                    if (versionedPackages == null) {
5100                        versionedPackages = new ArrayList<>();
5101                    }
5102                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5103                }
5104            }
5105        }
5106
5107        return versionedPackages;
5108    }
5109
5110    @Override
5111    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5112        if (!sUserManager.exists(userId)) return null;
5113        final int callingUid = Binder.getCallingUid();
5114        flags = updateFlagsForComponent(flags, userId, component);
5115        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5116                false /* requireFullPermission */, false /* checkShell */, "get service info");
5117        synchronized (mPackages) {
5118            PackageParser.Service s = mServices.mServices.get(component);
5119            if (DEBUG_PACKAGE_INFO) Log.v(
5120                TAG, "getServiceInfo " + component + ": " + s);
5121            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5122                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5123                if (ps == null) return null;
5124                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5125                    return null;
5126                }
5127                return PackageParser.generateServiceInfo(
5128                        s, flags, ps.readUserState(userId), userId);
5129            }
5130        }
5131        return null;
5132    }
5133
5134    @Override
5135    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5136        if (!sUserManager.exists(userId)) return null;
5137        final int callingUid = Binder.getCallingUid();
5138        flags = updateFlagsForComponent(flags, userId, component);
5139        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5140                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5141        synchronized (mPackages) {
5142            PackageParser.Provider p = mProviders.mProviders.get(component);
5143            if (DEBUG_PACKAGE_INFO) Log.v(
5144                TAG, "getProviderInfo " + component + ": " + p);
5145            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5146                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5147                if (ps == null) return null;
5148                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5149                    return null;
5150                }
5151                return PackageParser.generateProviderInfo(
5152                        p, flags, ps.readUserState(userId), userId);
5153            }
5154        }
5155        return null;
5156    }
5157
5158    @Override
5159    public String[] getSystemSharedLibraryNames() {
5160        // allow instant applications
5161        synchronized (mPackages) {
5162            Set<String> libs = null;
5163            final int libCount = mSharedLibraries.size();
5164            for (int i = 0; i < libCount; i++) {
5165                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5166                if (versionedLib == null) {
5167                    continue;
5168                }
5169                final int versionCount = versionedLib.size();
5170                for (int j = 0; j < versionCount; j++) {
5171                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5172                    if (!libEntry.info.isStatic()) {
5173                        if (libs == null) {
5174                            libs = new ArraySet<>();
5175                        }
5176                        libs.add(libEntry.info.getName());
5177                        break;
5178                    }
5179                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5180                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5181                            UserHandle.getUserId(Binder.getCallingUid()),
5182                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5183                        if (libs == null) {
5184                            libs = new ArraySet<>();
5185                        }
5186                        libs.add(libEntry.info.getName());
5187                        break;
5188                    }
5189                }
5190            }
5191
5192            if (libs != null) {
5193                String[] libsArray = new String[libs.size()];
5194                libs.toArray(libsArray);
5195                return libsArray;
5196            }
5197
5198            return null;
5199        }
5200    }
5201
5202    @Override
5203    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5204        // allow instant applications
5205        synchronized (mPackages) {
5206            return mServicesSystemSharedLibraryPackageName;
5207        }
5208    }
5209
5210    @Override
5211    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5212        // allow instant applications
5213        synchronized (mPackages) {
5214            return mSharedSystemSharedLibraryPackageName;
5215        }
5216    }
5217
5218    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5219        for (int i = userList.length - 1; i >= 0; --i) {
5220            final int userId = userList[i];
5221            // don't add instant app to the list of updates
5222            if (pkgSetting.getInstantApp(userId)) {
5223                continue;
5224            }
5225            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5226            if (changedPackages == null) {
5227                changedPackages = new SparseArray<>();
5228                mChangedPackages.put(userId, changedPackages);
5229            }
5230            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5231            if (sequenceNumbers == null) {
5232                sequenceNumbers = new HashMap<>();
5233                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5234            }
5235            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5236            if (sequenceNumber != null) {
5237                changedPackages.remove(sequenceNumber);
5238            }
5239            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5240            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5241        }
5242        mChangedPackagesSequenceNumber++;
5243    }
5244
5245    @Override
5246    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5247        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5248            return null;
5249        }
5250        synchronized (mPackages) {
5251            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5252                return null;
5253            }
5254            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5255            if (changedPackages == null) {
5256                return null;
5257            }
5258            final List<String> packageNames =
5259                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5260            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5261                final String packageName = changedPackages.get(i);
5262                if (packageName != null) {
5263                    packageNames.add(packageName);
5264                }
5265            }
5266            return packageNames.isEmpty()
5267                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5268        }
5269    }
5270
5271    @Override
5272    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5273        // allow instant applications
5274        ArrayList<FeatureInfo> res;
5275        synchronized (mAvailableFeatures) {
5276            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5277            res.addAll(mAvailableFeatures.values());
5278        }
5279        final FeatureInfo fi = new FeatureInfo();
5280        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5281                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5282        res.add(fi);
5283
5284        return new ParceledListSlice<>(res);
5285    }
5286
5287    @Override
5288    public boolean hasSystemFeature(String name, int version) {
5289        // allow instant applications
5290        synchronized (mAvailableFeatures) {
5291            final FeatureInfo feat = mAvailableFeatures.get(name);
5292            if (feat == null) {
5293                return false;
5294            } else {
5295                return feat.version >= version;
5296            }
5297        }
5298    }
5299
5300    @Override
5301    public int checkPermission(String permName, String pkgName, int userId) {
5302        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5303    }
5304
5305    @Override
5306    public int checkUidPermission(String permName, int uid) {
5307        synchronized (mPackages) {
5308            final String[] packageNames = getPackagesForUid(uid);
5309            final PackageParser.Package pkg = (packageNames != null && packageNames.length > 0)
5310                    ? mPackages.get(packageNames[0])
5311                    : null;
5312            return mPermissionManager.checkUidPermission(permName, pkg, uid, getCallingUid());
5313        }
5314    }
5315
5316    @Override
5317    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5318        if (UserHandle.getCallingUserId() != userId) {
5319            mContext.enforceCallingPermission(
5320                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5321                    "isPermissionRevokedByPolicy for user " + userId);
5322        }
5323
5324        if (checkPermission(permission, packageName, userId)
5325                == PackageManager.PERMISSION_GRANTED) {
5326            return false;
5327        }
5328
5329        final int callingUid = Binder.getCallingUid();
5330        if (getInstantAppPackageName(callingUid) != null) {
5331            if (!isCallerSameApp(packageName, callingUid)) {
5332                return false;
5333            }
5334        } else {
5335            if (isInstantApp(packageName, userId)) {
5336                return false;
5337            }
5338        }
5339
5340        final long identity = Binder.clearCallingIdentity();
5341        try {
5342            final int flags = getPermissionFlags(permission, packageName, userId);
5343            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5344        } finally {
5345            Binder.restoreCallingIdentity(identity);
5346        }
5347    }
5348
5349    @Override
5350    public String getPermissionControllerPackageName() {
5351        synchronized (mPackages) {
5352            return mRequiredInstallerPackage;
5353        }
5354    }
5355
5356    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5357        return mPermissionManager.addDynamicPermission(
5358                info, async, getCallingUid(), new PermissionCallback() {
5359                    @Override
5360                    public void onPermissionChanged() {
5361                        if (!async) {
5362                            mSettings.writeLPr();
5363                        } else {
5364                            scheduleWriteSettingsLocked();
5365                        }
5366                    }
5367                });
5368    }
5369
5370    @Override
5371    public boolean addPermission(PermissionInfo info) {
5372        synchronized (mPackages) {
5373            return addDynamicPermission(info, false);
5374        }
5375    }
5376
5377    @Override
5378    public boolean addPermissionAsync(PermissionInfo info) {
5379        synchronized (mPackages) {
5380            return addDynamicPermission(info, true);
5381        }
5382    }
5383
5384    @Override
5385    public void removePermission(String permName) {
5386        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5387    }
5388
5389    @Override
5390    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5391        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5392                getCallingUid(), userId, mPermissionCallback);
5393    }
5394
5395    @Override
5396    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5397        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5398                getCallingUid(), userId, mPermissionCallback);
5399    }
5400
5401    @Override
5402    public void resetRuntimePermissions() {
5403        mContext.enforceCallingOrSelfPermission(
5404                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5405                "revokeRuntimePermission");
5406
5407        int callingUid = Binder.getCallingUid();
5408        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5409            mContext.enforceCallingOrSelfPermission(
5410                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5411                    "resetRuntimePermissions");
5412        }
5413
5414        synchronized (mPackages) {
5415            mPermissionManager.updateAllPermissions(
5416                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5417                    mPermissionCallback);
5418            for (int userId : UserManagerService.getInstance().getUserIds()) {
5419                final int packageCount = mPackages.size();
5420                for (int i = 0; i < packageCount; i++) {
5421                    PackageParser.Package pkg = mPackages.valueAt(i);
5422                    if (!(pkg.mExtras instanceof PackageSetting)) {
5423                        continue;
5424                    }
5425                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5426                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5427                }
5428            }
5429        }
5430    }
5431
5432    @Override
5433    public int getPermissionFlags(String permName, String packageName, int userId) {
5434        return mPermissionManager.getPermissionFlags(
5435                permName, packageName, getCallingUid(), userId);
5436    }
5437
5438    @Override
5439    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5440            int flagValues, int userId) {
5441        mPermissionManager.updatePermissionFlags(
5442                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5443                mPermissionCallback);
5444    }
5445
5446    /**
5447     * Update the permission flags for all packages and runtime permissions of a user in order
5448     * to allow device or profile owner to remove POLICY_FIXED.
5449     */
5450    @Override
5451    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5452        synchronized (mPackages) {
5453            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5454                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5455                    mPermissionCallback);
5456            if (changed) {
5457                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5458            }
5459        }
5460    }
5461
5462    @Override
5463    public boolean shouldShowRequestPermissionRationale(String permissionName,
5464            String packageName, int userId) {
5465        if (UserHandle.getCallingUserId() != userId) {
5466            mContext.enforceCallingPermission(
5467                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5468                    "canShowRequestPermissionRationale for user " + userId);
5469        }
5470
5471        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5472        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5473            return false;
5474        }
5475
5476        if (checkPermission(permissionName, packageName, userId)
5477                == PackageManager.PERMISSION_GRANTED) {
5478            return false;
5479        }
5480
5481        final int flags;
5482
5483        final long identity = Binder.clearCallingIdentity();
5484        try {
5485            flags = getPermissionFlags(permissionName,
5486                    packageName, userId);
5487        } finally {
5488            Binder.restoreCallingIdentity(identity);
5489        }
5490
5491        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5492                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5493                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5494
5495        if ((flags & fixedFlags) != 0) {
5496            return false;
5497        }
5498
5499        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5500    }
5501
5502    @Override
5503    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5504        mContext.enforceCallingOrSelfPermission(
5505                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5506                "addOnPermissionsChangeListener");
5507
5508        synchronized (mPackages) {
5509            mOnPermissionChangeListeners.addListenerLocked(listener);
5510        }
5511    }
5512
5513    @Override
5514    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5515        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5516            throw new SecurityException("Instant applications don't have access to this method");
5517        }
5518        synchronized (mPackages) {
5519            mOnPermissionChangeListeners.removeListenerLocked(listener);
5520        }
5521    }
5522
5523    @Override
5524    public boolean isProtectedBroadcast(String actionName) {
5525        // allow instant applications
5526        synchronized (mProtectedBroadcasts) {
5527            if (mProtectedBroadcasts.contains(actionName)) {
5528                return true;
5529            } else if (actionName != null) {
5530                // TODO: remove these terrible hacks
5531                if (actionName.startsWith("android.net.netmon.lingerExpired")
5532                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5533                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5534                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5535                    return true;
5536                }
5537            }
5538        }
5539        return false;
5540    }
5541
5542    @Override
5543    public int checkSignatures(String pkg1, String pkg2) {
5544        synchronized (mPackages) {
5545            final PackageParser.Package p1 = mPackages.get(pkg1);
5546            final PackageParser.Package p2 = mPackages.get(pkg2);
5547            if (p1 == null || p1.mExtras == null
5548                    || p2 == null || p2.mExtras == null) {
5549                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5550            }
5551            final int callingUid = Binder.getCallingUid();
5552            final int callingUserId = UserHandle.getUserId(callingUid);
5553            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5554            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5555            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5556                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5557                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5558            }
5559            return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures);
5560        }
5561    }
5562
5563    @Override
5564    public int checkUidSignatures(int uid1, int uid2) {
5565        final int callingUid = Binder.getCallingUid();
5566        final int callingUserId = UserHandle.getUserId(callingUid);
5567        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5568        // Map to base uids.
5569        uid1 = UserHandle.getAppId(uid1);
5570        uid2 = UserHandle.getAppId(uid2);
5571        // reader
5572        synchronized (mPackages) {
5573            Signature[] s1;
5574            Signature[] s2;
5575            Object obj = mSettings.getUserIdLPr(uid1);
5576            if (obj != null) {
5577                if (obj instanceof SharedUserSetting) {
5578                    if (isCallerInstantApp) {
5579                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5580                    }
5581                    s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5582                } else if (obj instanceof PackageSetting) {
5583                    final PackageSetting ps = (PackageSetting) obj;
5584                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5585                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5586                    }
5587                    s1 = ps.signatures.mSigningDetails.signatures;
5588                } else {
5589                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5590                }
5591            } else {
5592                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5593            }
5594            obj = mSettings.getUserIdLPr(uid2);
5595            if (obj != null) {
5596                if (obj instanceof SharedUserSetting) {
5597                    if (isCallerInstantApp) {
5598                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5599                    }
5600                    s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5601                } else if (obj instanceof PackageSetting) {
5602                    final PackageSetting ps = (PackageSetting) obj;
5603                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5604                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5605                    }
5606                    s2 = ps.signatures.mSigningDetails.signatures;
5607                } else {
5608                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5609                }
5610            } else {
5611                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5612            }
5613            return compareSignatures(s1, s2);
5614        }
5615    }
5616
5617    @Override
5618    public boolean hasSigningCertificate(
5619            String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) {
5620
5621        synchronized (mPackages) {
5622            final PackageParser.Package p = mPackages.get(packageName);
5623            if (p == null || p.mExtras == null) {
5624                return false;
5625            }
5626            final int callingUid = Binder.getCallingUid();
5627            final int callingUserId = UserHandle.getUserId(callingUid);
5628            final PackageSetting ps = (PackageSetting) p.mExtras;
5629            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5630                return false;
5631            }
5632            switch (type) {
5633                case CERT_INPUT_RAW_X509:
5634                    return p.mSigningDetails.hasCertificate(certificate);
5635                case CERT_INPUT_SHA256:
5636                    return p.mSigningDetails.hasSha256Certificate(certificate);
5637                default:
5638                    return false;
5639            }
5640        }
5641    }
5642
5643    @Override
5644    public boolean hasUidSigningCertificate(
5645            int uid, byte[] certificate, @PackageManager.CertificateInputType int type) {
5646        final int callingUid = Binder.getCallingUid();
5647        final int callingUserId = UserHandle.getUserId(callingUid);
5648        // Map to base uids.
5649        uid = UserHandle.getAppId(uid);
5650        // reader
5651        synchronized (mPackages) {
5652            final PackageParser.SigningDetails signingDetails;
5653            final Object obj = mSettings.getUserIdLPr(uid);
5654            if (obj != null) {
5655                if (obj instanceof SharedUserSetting) {
5656                    final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5657                    if (isCallerInstantApp) {
5658                        return false;
5659                    }
5660                    signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails;
5661                } else if (obj instanceof PackageSetting) {
5662                    final PackageSetting ps = (PackageSetting) obj;
5663                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5664                        return false;
5665                    }
5666                    signingDetails = ps.signatures.mSigningDetails;
5667                } else {
5668                    return false;
5669                }
5670            } else {
5671                return false;
5672            }
5673            switch (type) {
5674                case CERT_INPUT_RAW_X509:
5675                    return signingDetails.hasCertificate(certificate);
5676                case CERT_INPUT_SHA256:
5677                    return signingDetails.hasSha256Certificate(certificate);
5678                default:
5679                    return false;
5680            }
5681        }
5682    }
5683
5684    /**
5685     * This method should typically only be used when granting or revoking
5686     * permissions, since the app may immediately restart after this call.
5687     * <p>
5688     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5689     * guard your work against the app being relaunched.
5690     */
5691    private void killUid(int appId, int userId, String reason) {
5692        final long identity = Binder.clearCallingIdentity();
5693        try {
5694            IActivityManager am = ActivityManager.getService();
5695            if (am != null) {
5696                try {
5697                    am.killUid(appId, userId, reason);
5698                } catch (RemoteException e) {
5699                    /* ignore - same process */
5700                }
5701            }
5702        } finally {
5703            Binder.restoreCallingIdentity(identity);
5704        }
5705    }
5706
5707    /**
5708     * If the database version for this type of package (internal storage or
5709     * external storage) is less than the version where package signatures
5710     * were updated, return true.
5711     */
5712    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5713        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5714        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5715    }
5716
5717    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5718        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5719        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5720    }
5721
5722    @Override
5723    public List<String> getAllPackages() {
5724        final int callingUid = Binder.getCallingUid();
5725        final int callingUserId = UserHandle.getUserId(callingUid);
5726        synchronized (mPackages) {
5727            if (canViewInstantApps(callingUid, callingUserId)) {
5728                return new ArrayList<String>(mPackages.keySet());
5729            }
5730            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5731            final List<String> result = new ArrayList<>();
5732            if (instantAppPkgName != null) {
5733                // caller is an instant application; filter unexposed applications
5734                for (PackageParser.Package pkg : mPackages.values()) {
5735                    if (!pkg.visibleToInstantApps) {
5736                        continue;
5737                    }
5738                    result.add(pkg.packageName);
5739                }
5740            } else {
5741                // caller is a normal application; filter instant applications
5742                for (PackageParser.Package pkg : mPackages.values()) {
5743                    final PackageSetting ps =
5744                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5745                    if (ps != null
5746                            && ps.getInstantApp(callingUserId)
5747                            && !mInstantAppRegistry.isInstantAccessGranted(
5748                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5749                        continue;
5750                    }
5751                    result.add(pkg.packageName);
5752                }
5753            }
5754            return result;
5755        }
5756    }
5757
5758    @Override
5759    public String[] getPackagesForUid(int uid) {
5760        final int callingUid = Binder.getCallingUid();
5761        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5762        final int userId = UserHandle.getUserId(uid);
5763        uid = UserHandle.getAppId(uid);
5764        // reader
5765        synchronized (mPackages) {
5766            Object obj = mSettings.getUserIdLPr(uid);
5767            if (obj instanceof SharedUserSetting) {
5768                if (isCallerInstantApp) {
5769                    return null;
5770                }
5771                final SharedUserSetting sus = (SharedUserSetting) obj;
5772                final int N = sus.packages.size();
5773                String[] res = new String[N];
5774                final Iterator<PackageSetting> it = sus.packages.iterator();
5775                int i = 0;
5776                while (it.hasNext()) {
5777                    PackageSetting ps = it.next();
5778                    if (ps.getInstalled(userId)) {
5779                        res[i++] = ps.name;
5780                    } else {
5781                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5782                    }
5783                }
5784                return res;
5785            } else if (obj instanceof PackageSetting) {
5786                final PackageSetting ps = (PackageSetting) obj;
5787                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5788                    return new String[]{ps.name};
5789                }
5790            }
5791        }
5792        return null;
5793    }
5794
5795    @Override
5796    public String getNameForUid(int uid) {
5797        final int callingUid = Binder.getCallingUid();
5798        if (getInstantAppPackageName(callingUid) != null) {
5799            return null;
5800        }
5801        synchronized (mPackages) {
5802            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5803            if (obj instanceof SharedUserSetting) {
5804                final SharedUserSetting sus = (SharedUserSetting) obj;
5805                return sus.name + ":" + sus.userId;
5806            } else if (obj instanceof PackageSetting) {
5807                final PackageSetting ps = (PackageSetting) obj;
5808                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5809                    return null;
5810                }
5811                return ps.name;
5812            }
5813            return null;
5814        }
5815    }
5816
5817    @Override
5818    public String[] getNamesForUids(int[] uids) {
5819        if (uids == null || uids.length == 0) {
5820            return null;
5821        }
5822        final int callingUid = Binder.getCallingUid();
5823        if (getInstantAppPackageName(callingUid) != null) {
5824            return null;
5825        }
5826        final String[] names = new String[uids.length];
5827        synchronized (mPackages) {
5828            for (int i = uids.length - 1; i >= 0; i--) {
5829                final int uid = uids[i];
5830                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5831                if (obj instanceof SharedUserSetting) {
5832                    final SharedUserSetting sus = (SharedUserSetting) obj;
5833                    names[i] = "shared:" + sus.name;
5834                } else if (obj instanceof PackageSetting) {
5835                    final PackageSetting ps = (PackageSetting) obj;
5836                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5837                        names[i] = null;
5838                    } else {
5839                        names[i] = ps.name;
5840                    }
5841                } else {
5842                    names[i] = null;
5843                }
5844            }
5845        }
5846        return names;
5847    }
5848
5849    @Override
5850    public int getUidForSharedUser(String sharedUserName) {
5851        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5852            return -1;
5853        }
5854        if (sharedUserName == null) {
5855            return -1;
5856        }
5857        // reader
5858        synchronized (mPackages) {
5859            SharedUserSetting suid;
5860            try {
5861                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5862                if (suid != null) {
5863                    return suid.userId;
5864                }
5865            } catch (PackageManagerException ignore) {
5866                // can't happen, but, still need to catch it
5867            }
5868            return -1;
5869        }
5870    }
5871
5872    @Override
5873    public int getFlagsForUid(int uid) {
5874        final int callingUid = Binder.getCallingUid();
5875        if (getInstantAppPackageName(callingUid) != null) {
5876            return 0;
5877        }
5878        synchronized (mPackages) {
5879            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5880            if (obj instanceof SharedUserSetting) {
5881                final SharedUserSetting sus = (SharedUserSetting) obj;
5882                return sus.pkgFlags;
5883            } else if (obj instanceof PackageSetting) {
5884                final PackageSetting ps = (PackageSetting) obj;
5885                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5886                    return 0;
5887                }
5888                return ps.pkgFlags;
5889            }
5890        }
5891        return 0;
5892    }
5893
5894    @Override
5895    public int getPrivateFlagsForUid(int uid) {
5896        final int callingUid = Binder.getCallingUid();
5897        if (getInstantAppPackageName(callingUid) != null) {
5898            return 0;
5899        }
5900        synchronized (mPackages) {
5901            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5902            if (obj instanceof SharedUserSetting) {
5903                final SharedUserSetting sus = (SharedUserSetting) obj;
5904                return sus.pkgPrivateFlags;
5905            } else if (obj instanceof PackageSetting) {
5906                final PackageSetting ps = (PackageSetting) obj;
5907                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5908                    return 0;
5909                }
5910                return ps.pkgPrivateFlags;
5911            }
5912        }
5913        return 0;
5914    }
5915
5916    @Override
5917    public boolean isUidPrivileged(int uid) {
5918        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5919            return false;
5920        }
5921        uid = UserHandle.getAppId(uid);
5922        // reader
5923        synchronized (mPackages) {
5924            Object obj = mSettings.getUserIdLPr(uid);
5925            if (obj instanceof SharedUserSetting) {
5926                final SharedUserSetting sus = (SharedUserSetting) obj;
5927                final Iterator<PackageSetting> it = sus.packages.iterator();
5928                while (it.hasNext()) {
5929                    if (it.next().isPrivileged()) {
5930                        return true;
5931                    }
5932                }
5933            } else if (obj instanceof PackageSetting) {
5934                final PackageSetting ps = (PackageSetting) obj;
5935                return ps.isPrivileged();
5936            }
5937        }
5938        return false;
5939    }
5940
5941    @Override
5942    public String[] getAppOpPermissionPackages(String permName) {
5943        return mPermissionManager.getAppOpPermissionPackages(permName);
5944    }
5945
5946    @Override
5947    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5948            int flags, int userId) {
5949        return resolveIntentInternal(intent, resolvedType, flags, userId, false,
5950                Binder.getCallingUid());
5951    }
5952
5953    /**
5954     * Normally instant apps can only be resolved when they're visible to the caller.
5955     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5956     * since we need to allow the system to start any installed application.
5957     */
5958    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5959            int flags, int userId, boolean resolveForStart, int filterCallingUid) {
5960        try {
5961            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5962
5963            if (!sUserManager.exists(userId)) return null;
5964            final int callingUid = Binder.getCallingUid();
5965            flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart);
5966            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5967                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5968
5969            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5970            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5971                    flags, filterCallingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5972            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5973
5974            final ResolveInfo bestChoice =
5975                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5976            return bestChoice;
5977        } finally {
5978            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5979        }
5980    }
5981
5982    @Override
5983    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5984        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5985            throw new SecurityException(
5986                    "findPersistentPreferredActivity can only be run by the system");
5987        }
5988        if (!sUserManager.exists(userId)) {
5989            return null;
5990        }
5991        final int callingUid = Binder.getCallingUid();
5992        intent = updateIntentForResolve(intent);
5993        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5994        final int flags = updateFlagsForResolve(
5995                0, userId, intent, callingUid, false /*includeInstantApps*/);
5996        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5997                userId);
5998        synchronized (mPackages) {
5999            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6000                    userId);
6001        }
6002    }
6003
6004    @Override
6005    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6006            IntentFilter filter, int match, ComponentName activity) {
6007        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6008            return;
6009        }
6010        final int userId = UserHandle.getCallingUserId();
6011        if (DEBUG_PREFERRED) {
6012            Log.v(TAG, "setLastChosenActivity intent=" + intent
6013                + " resolvedType=" + resolvedType
6014                + " flags=" + flags
6015                + " filter=" + filter
6016                + " match=" + match
6017                + " activity=" + activity);
6018            filter.dump(new PrintStreamPrinter(System.out), "    ");
6019        }
6020        intent.setComponent(null);
6021        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6022                userId);
6023        // Find any earlier preferred or last chosen entries and nuke them
6024        findPreferredActivity(intent, resolvedType,
6025                flags, query, 0, false, true, false, userId);
6026        // Add the new activity as the last chosen for this filter
6027        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6028                "Setting last chosen");
6029    }
6030
6031    @Override
6032    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6033        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6034            return null;
6035        }
6036        final int userId = UserHandle.getCallingUserId();
6037        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6038        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6039                userId);
6040        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6041                false, false, false, userId);
6042    }
6043
6044    /**
6045     * Returns whether or not instant apps have been disabled remotely.
6046     */
6047    private boolean areWebInstantAppsDisabled() {
6048        return mWebInstantAppsDisabled;
6049    }
6050
6051    private boolean isInstantAppResolutionAllowed(
6052            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6053            boolean skipPackageCheck) {
6054        if (mInstantAppResolverConnection == null) {
6055            return false;
6056        }
6057        if (mInstantAppInstallerActivity == null) {
6058            return false;
6059        }
6060        if (intent.getComponent() != null) {
6061            return false;
6062        }
6063        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6064            return false;
6065        }
6066        if (!skipPackageCheck && intent.getPackage() != null) {
6067            return false;
6068        }
6069        if (!intent.isWebIntent()) {
6070            // for non web intents, we should not resolve externally if an app already exists to
6071            // handle it or if the caller didn't explicitly request it.
6072            if ((resolvedActivities != null && resolvedActivities.size() != 0)
6073                    || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) {
6074                return false;
6075            }
6076        } else {
6077            if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) {
6078                return false;
6079            } else if (areWebInstantAppsDisabled()) {
6080                return false;
6081            }
6082        }
6083        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6084        // Or if there's already an ephemeral app installed that handles the action
6085        synchronized (mPackages) {
6086            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6087            for (int n = 0; n < count; n++) {
6088                final ResolveInfo info = resolvedActivities.get(n);
6089                final String packageName = info.activityInfo.packageName;
6090                final PackageSetting ps = mSettings.mPackages.get(packageName);
6091                if (ps != null) {
6092                    // only check domain verification status if the app is not a browser
6093                    if (!info.handleAllWebDataURI) {
6094                        // Try to get the status from User settings first
6095                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6096                        final int status = (int) (packedStatus >> 32);
6097                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6098                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6099                            if (DEBUG_INSTANT) {
6100                                Slog.v(TAG, "DENY instant app;"
6101                                    + " pkg: " + packageName + ", status: " + status);
6102                            }
6103                            return false;
6104                        }
6105                    }
6106                    if (ps.getInstantApp(userId)) {
6107                        if (DEBUG_INSTANT) {
6108                            Slog.v(TAG, "DENY instant app installed;"
6109                                    + " pkg: " + packageName);
6110                        }
6111                        return false;
6112                    }
6113                }
6114            }
6115        }
6116        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6117        return true;
6118    }
6119
6120    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6121            Intent origIntent, String resolvedType, String callingPackage,
6122            Bundle verificationBundle, int userId) {
6123        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6124                new InstantAppRequest(responseObj, origIntent, resolvedType,
6125                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6126        mHandler.sendMessage(msg);
6127    }
6128
6129    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6130            int flags, List<ResolveInfo> query, int userId) {
6131        if (query != null) {
6132            final int N = query.size();
6133            if (N == 1) {
6134                return query.get(0);
6135            } else if (N > 1) {
6136                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6137                // If there is more than one activity with the same priority,
6138                // then let the user decide between them.
6139                ResolveInfo r0 = query.get(0);
6140                ResolveInfo r1 = query.get(1);
6141                if (DEBUG_INTENT_MATCHING || debug) {
6142                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6143                            + r1.activityInfo.name + "=" + r1.priority);
6144                }
6145                // If the first activity has a higher priority, or a different
6146                // default, then it is always desirable to pick it.
6147                if (r0.priority != r1.priority
6148                        || r0.preferredOrder != r1.preferredOrder
6149                        || r0.isDefault != r1.isDefault) {
6150                    return query.get(0);
6151                }
6152                // If we have saved a preference for a preferred activity for
6153                // this Intent, use that.
6154                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6155                        flags, query, r0.priority, true, false, debug, userId);
6156                if (ri != null) {
6157                    return ri;
6158                }
6159                // If we have an ephemeral app, use it
6160                for (int i = 0; i < N; i++) {
6161                    ri = query.get(i);
6162                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6163                        final String packageName = ri.activityInfo.packageName;
6164                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6165                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6166                        final int status = (int)(packedStatus >> 32);
6167                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6168                            return ri;
6169                        }
6170                    }
6171                }
6172                ri = new ResolveInfo(mResolveInfo);
6173                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6174                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6175                // If all of the options come from the same package, show the application's
6176                // label and icon instead of the generic resolver's.
6177                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6178                // and then throw away the ResolveInfo itself, meaning that the caller loses
6179                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6180                // a fallback for this case; we only set the target package's resources on
6181                // the ResolveInfo, not the ActivityInfo.
6182                final String intentPackage = intent.getPackage();
6183                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6184                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6185                    ri.resolvePackageName = intentPackage;
6186                    if (userNeedsBadging(userId)) {
6187                        ri.noResourceId = true;
6188                    } else {
6189                        ri.icon = appi.icon;
6190                    }
6191                    ri.iconResourceId = appi.icon;
6192                    ri.labelRes = appi.labelRes;
6193                }
6194                ri.activityInfo.applicationInfo = new ApplicationInfo(
6195                        ri.activityInfo.applicationInfo);
6196                if (userId != 0) {
6197                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6198                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6199                }
6200                // Make sure that the resolver is displayable in car mode
6201                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6202                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6203                return ri;
6204            }
6205        }
6206        return null;
6207    }
6208
6209    /**
6210     * Return true if the given list is not empty and all of its contents have
6211     * an activityInfo with the given package name.
6212     */
6213    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6214        if (ArrayUtils.isEmpty(list)) {
6215            return false;
6216        }
6217        for (int i = 0, N = list.size(); i < N; i++) {
6218            final ResolveInfo ri = list.get(i);
6219            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6220            if (ai == null || !packageName.equals(ai.packageName)) {
6221                return false;
6222            }
6223        }
6224        return true;
6225    }
6226
6227    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6228            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6229        final int N = query.size();
6230        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6231                .get(userId);
6232        // Get the list of persistent preferred activities that handle the intent
6233        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6234        List<PersistentPreferredActivity> pprefs = ppir != null
6235                ? ppir.queryIntent(intent, resolvedType,
6236                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6237                        userId)
6238                : null;
6239        if (pprefs != null && pprefs.size() > 0) {
6240            final int M = pprefs.size();
6241            for (int i=0; i<M; i++) {
6242                final PersistentPreferredActivity ppa = pprefs.get(i);
6243                if (DEBUG_PREFERRED || debug) {
6244                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6245                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6246                            + "\n  component=" + ppa.mComponent);
6247                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6248                }
6249                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6250                        flags | MATCH_DISABLED_COMPONENTS, userId);
6251                if (DEBUG_PREFERRED || debug) {
6252                    Slog.v(TAG, "Found persistent preferred activity:");
6253                    if (ai != null) {
6254                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6255                    } else {
6256                        Slog.v(TAG, "  null");
6257                    }
6258                }
6259                if (ai == null) {
6260                    // This previously registered persistent preferred activity
6261                    // component is no longer known. Ignore it and do NOT remove it.
6262                    continue;
6263                }
6264                for (int j=0; j<N; j++) {
6265                    final ResolveInfo ri = query.get(j);
6266                    if (!ri.activityInfo.applicationInfo.packageName
6267                            .equals(ai.applicationInfo.packageName)) {
6268                        continue;
6269                    }
6270                    if (!ri.activityInfo.name.equals(ai.name)) {
6271                        continue;
6272                    }
6273                    //  Found a persistent preference that can handle the intent.
6274                    if (DEBUG_PREFERRED || debug) {
6275                        Slog.v(TAG, "Returning persistent preferred activity: " +
6276                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6277                    }
6278                    return ri;
6279                }
6280            }
6281        }
6282        return null;
6283    }
6284
6285    // TODO: handle preferred activities missing while user has amnesia
6286    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6287            List<ResolveInfo> query, int priority, boolean always,
6288            boolean removeMatches, boolean debug, int userId) {
6289        if (!sUserManager.exists(userId)) return null;
6290        final int callingUid = Binder.getCallingUid();
6291        flags = updateFlagsForResolve(
6292                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6293        intent = updateIntentForResolve(intent);
6294        // writer
6295        synchronized (mPackages) {
6296            // Try to find a matching persistent preferred activity.
6297            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6298                    debug, userId);
6299
6300            // If a persistent preferred activity matched, use it.
6301            if (pri != null) {
6302                return pri;
6303            }
6304
6305            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6306            // Get the list of preferred activities that handle the intent
6307            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6308            List<PreferredActivity> prefs = pir != null
6309                    ? pir.queryIntent(intent, resolvedType,
6310                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6311                            userId)
6312                    : null;
6313            if (prefs != null && prefs.size() > 0) {
6314                boolean changed = false;
6315                try {
6316                    // First figure out how good the original match set is.
6317                    // We will only allow preferred activities that came
6318                    // from the same match quality.
6319                    int match = 0;
6320
6321                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6322
6323                    final int N = query.size();
6324                    for (int j=0; j<N; j++) {
6325                        final ResolveInfo ri = query.get(j);
6326                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6327                                + ": 0x" + Integer.toHexString(match));
6328                        if (ri.match > match) {
6329                            match = ri.match;
6330                        }
6331                    }
6332
6333                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6334                            + Integer.toHexString(match));
6335
6336                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6337                    final int M = prefs.size();
6338                    for (int i=0; i<M; i++) {
6339                        final PreferredActivity pa = prefs.get(i);
6340                        if (DEBUG_PREFERRED || debug) {
6341                            Slog.v(TAG, "Checking PreferredActivity ds="
6342                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6343                                    + "\n  component=" + pa.mPref.mComponent);
6344                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6345                        }
6346                        if (pa.mPref.mMatch != match) {
6347                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6348                                    + Integer.toHexString(pa.mPref.mMatch));
6349                            continue;
6350                        }
6351                        // If it's not an "always" type preferred activity and that's what we're
6352                        // looking for, skip it.
6353                        if (always && !pa.mPref.mAlways) {
6354                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6355                            continue;
6356                        }
6357                        final ActivityInfo ai = getActivityInfo(
6358                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6359                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6360                                userId);
6361                        if (DEBUG_PREFERRED || debug) {
6362                            Slog.v(TAG, "Found preferred activity:");
6363                            if (ai != null) {
6364                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6365                            } else {
6366                                Slog.v(TAG, "  null");
6367                            }
6368                        }
6369                        if (ai == null) {
6370                            // This previously registered preferred activity
6371                            // component is no longer known.  Most likely an update
6372                            // to the app was installed and in the new version this
6373                            // component no longer exists.  Clean it up by removing
6374                            // it from the preferred activities list, and skip it.
6375                            Slog.w(TAG, "Removing dangling preferred activity: "
6376                                    + pa.mPref.mComponent);
6377                            pir.removeFilter(pa);
6378                            changed = true;
6379                            continue;
6380                        }
6381                        for (int j=0; j<N; j++) {
6382                            final ResolveInfo ri = query.get(j);
6383                            if (!ri.activityInfo.applicationInfo.packageName
6384                                    .equals(ai.applicationInfo.packageName)) {
6385                                continue;
6386                            }
6387                            if (!ri.activityInfo.name.equals(ai.name)) {
6388                                continue;
6389                            }
6390
6391                            if (removeMatches) {
6392                                pir.removeFilter(pa);
6393                                changed = true;
6394                                if (DEBUG_PREFERRED) {
6395                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6396                                }
6397                                break;
6398                            }
6399
6400                            // Okay we found a previously set preferred or last chosen app.
6401                            // If the result set is different from when this
6402                            // was created, and is not a subset of the preferred set, we need to
6403                            // clear it and re-ask the user their preference, if we're looking for
6404                            // an "always" type entry.
6405                            if (always && !pa.mPref.sameSet(query)) {
6406                                if (pa.mPref.isSuperset(query)) {
6407                                    // some components of the set are no longer present in
6408                                    // the query, but the preferred activity can still be reused
6409                                    if (DEBUG_PREFERRED) {
6410                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6411                                                + " still valid as only non-preferred components"
6412                                                + " were removed for " + intent + " type "
6413                                                + resolvedType);
6414                                    }
6415                                    // remove obsolete components and re-add the up-to-date filter
6416                                    PreferredActivity freshPa = new PreferredActivity(pa,
6417                                            pa.mPref.mMatch,
6418                                            pa.mPref.discardObsoleteComponents(query),
6419                                            pa.mPref.mComponent,
6420                                            pa.mPref.mAlways);
6421                                    pir.removeFilter(pa);
6422                                    pir.addFilter(freshPa);
6423                                    changed = true;
6424                                } else {
6425                                    Slog.i(TAG,
6426                                            "Result set changed, dropping preferred activity for "
6427                                                    + intent + " type " + resolvedType);
6428                                    if (DEBUG_PREFERRED) {
6429                                        Slog.v(TAG, "Removing preferred activity since set changed "
6430                                                + pa.mPref.mComponent);
6431                                    }
6432                                    pir.removeFilter(pa);
6433                                    // Re-add the filter as a "last chosen" entry (!always)
6434                                    PreferredActivity lastChosen = new PreferredActivity(
6435                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6436                                    pir.addFilter(lastChosen);
6437                                    changed = true;
6438                                    return null;
6439                                }
6440                            }
6441
6442                            // Yay! Either the set matched or we're looking for the last chosen
6443                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6444                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6445                            return ri;
6446                        }
6447                    }
6448                } finally {
6449                    if (changed) {
6450                        if (DEBUG_PREFERRED) {
6451                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6452                        }
6453                        scheduleWritePackageRestrictionsLocked(userId);
6454                    }
6455                }
6456            }
6457        }
6458        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6459        return null;
6460    }
6461
6462    /*
6463     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6464     */
6465    @Override
6466    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6467            int targetUserId) {
6468        mContext.enforceCallingOrSelfPermission(
6469                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6470        List<CrossProfileIntentFilter> matches =
6471                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6472        if (matches != null) {
6473            int size = matches.size();
6474            for (int i = 0; i < size; i++) {
6475                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6476            }
6477        }
6478        if (intent.hasWebURI()) {
6479            // cross-profile app linking works only towards the parent.
6480            final int callingUid = Binder.getCallingUid();
6481            final UserInfo parent = getProfileParent(sourceUserId);
6482            synchronized(mPackages) {
6483                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6484                        false /*includeInstantApps*/);
6485                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6486                        intent, resolvedType, flags, sourceUserId, parent.id);
6487                return xpDomainInfo != null;
6488            }
6489        }
6490        return false;
6491    }
6492
6493    private UserInfo getProfileParent(int userId) {
6494        final long identity = Binder.clearCallingIdentity();
6495        try {
6496            return sUserManager.getProfileParent(userId);
6497        } finally {
6498            Binder.restoreCallingIdentity(identity);
6499        }
6500    }
6501
6502    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6503            String resolvedType, int userId) {
6504        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6505        if (resolver != null) {
6506            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6507        }
6508        return null;
6509    }
6510
6511    @Override
6512    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6513            String resolvedType, int flags, int userId) {
6514        try {
6515            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6516
6517            return new ParceledListSlice<>(
6518                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6519        } finally {
6520            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6521        }
6522    }
6523
6524    /**
6525     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6526     * instant, returns {@code null}.
6527     */
6528    private String getInstantAppPackageName(int callingUid) {
6529        synchronized (mPackages) {
6530            // If the caller is an isolated app use the owner's uid for the lookup.
6531            if (Process.isIsolated(callingUid)) {
6532                callingUid = mIsolatedOwners.get(callingUid);
6533            }
6534            final int appId = UserHandle.getAppId(callingUid);
6535            final Object obj = mSettings.getUserIdLPr(appId);
6536            if (obj instanceof PackageSetting) {
6537                final PackageSetting ps = (PackageSetting) obj;
6538                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6539                return isInstantApp ? ps.pkg.packageName : null;
6540            }
6541        }
6542        return null;
6543    }
6544
6545    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6546            String resolvedType, int flags, int userId) {
6547        return queryIntentActivitiesInternal(
6548                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6549                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6550    }
6551
6552    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6553            String resolvedType, int flags, int filterCallingUid, int userId,
6554            boolean resolveForStart, boolean allowDynamicSplits) {
6555        if (!sUserManager.exists(userId)) return Collections.emptyList();
6556        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6557        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6558                false /* requireFullPermission */, false /* checkShell */,
6559                "query intent activities");
6560        final String pkgName = intent.getPackage();
6561        ComponentName comp = intent.getComponent();
6562        if (comp == null) {
6563            if (intent.getSelector() != null) {
6564                intent = intent.getSelector();
6565                comp = intent.getComponent();
6566            }
6567        }
6568
6569        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6570                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6571        if (comp != null) {
6572            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6573            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6574            if (ai != null) {
6575                // When specifying an explicit component, we prevent the activity from being
6576                // used when either 1) the calling package is normal and the activity is within
6577                // an ephemeral application or 2) the calling package is ephemeral and the
6578                // activity is not visible to ephemeral applications.
6579                final boolean matchInstantApp =
6580                        (flags & PackageManager.MATCH_INSTANT) != 0;
6581                final boolean matchVisibleToInstantAppOnly =
6582                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6583                final boolean matchExplicitlyVisibleOnly =
6584                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6585                final boolean isCallerInstantApp =
6586                        instantAppPkgName != null;
6587                final boolean isTargetSameInstantApp =
6588                        comp.getPackageName().equals(instantAppPkgName);
6589                final boolean isTargetInstantApp =
6590                        (ai.applicationInfo.privateFlags
6591                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6592                final boolean isTargetVisibleToInstantApp =
6593                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6594                final boolean isTargetExplicitlyVisibleToInstantApp =
6595                        isTargetVisibleToInstantApp
6596                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6597                final boolean isTargetHiddenFromInstantApp =
6598                        !isTargetVisibleToInstantApp
6599                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6600                final boolean blockResolution =
6601                        !isTargetSameInstantApp
6602                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6603                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6604                                        && isTargetHiddenFromInstantApp));
6605                if (!blockResolution) {
6606                    final ResolveInfo ri = new ResolveInfo();
6607                    ri.activityInfo = ai;
6608                    list.add(ri);
6609                }
6610            }
6611            return applyPostResolutionFilter(
6612                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6613        }
6614
6615        // reader
6616        boolean sortResult = false;
6617        boolean addInstant = false;
6618        List<ResolveInfo> result;
6619        synchronized (mPackages) {
6620            if (pkgName == null) {
6621                List<CrossProfileIntentFilter> matchingFilters =
6622                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6623                // Check for results that need to skip the current profile.
6624                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6625                        resolvedType, flags, userId);
6626                if (xpResolveInfo != null) {
6627                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6628                    xpResult.add(xpResolveInfo);
6629                    return applyPostResolutionFilter(
6630                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6631                            allowDynamicSplits, filterCallingUid, userId, intent);
6632                }
6633
6634                // Check for results in the current profile.
6635                result = filterIfNotSystemUser(mActivities.queryIntent(
6636                        intent, resolvedType, flags, userId), userId);
6637                addInstant = isInstantAppResolutionAllowed(intent, result, userId,
6638                        false /*skipPackageCheck*/);
6639                // Check for cross profile results.
6640                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6641                xpResolveInfo = queryCrossProfileIntents(
6642                        matchingFilters, intent, resolvedType, flags, userId,
6643                        hasNonNegativePriorityResult);
6644                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6645                    boolean isVisibleToUser = filterIfNotSystemUser(
6646                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6647                    if (isVisibleToUser) {
6648                        result.add(xpResolveInfo);
6649                        sortResult = true;
6650                    }
6651                }
6652                if (intent.hasWebURI()) {
6653                    CrossProfileDomainInfo xpDomainInfo = null;
6654                    final UserInfo parent = getProfileParent(userId);
6655                    if (parent != null) {
6656                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6657                                flags, userId, parent.id);
6658                    }
6659                    if (xpDomainInfo != null) {
6660                        if (xpResolveInfo != null) {
6661                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6662                            // in the result.
6663                            result.remove(xpResolveInfo);
6664                        }
6665                        if (result.size() == 0 && !addInstant) {
6666                            // No result in current profile, but found candidate in parent user.
6667                            // And we are not going to add emphemeral app, so we can return the
6668                            // result straight away.
6669                            result.add(xpDomainInfo.resolveInfo);
6670                            return applyPostResolutionFilter(result, instantAppPkgName,
6671                                    allowDynamicSplits, filterCallingUid, userId, intent);
6672                        }
6673                    } else if (result.size() <= 1 && !addInstant) {
6674                        // No result in parent user and <= 1 result in current profile, and we
6675                        // are not going to add emphemeral app, so we can return the result without
6676                        // further processing.
6677                        return applyPostResolutionFilter(result, instantAppPkgName,
6678                                allowDynamicSplits, filterCallingUid, userId, intent);
6679                    }
6680                    // We have more than one candidate (combining results from current and parent
6681                    // profile), so we need filtering and sorting.
6682                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6683                            intent, flags, result, xpDomainInfo, userId);
6684                    sortResult = true;
6685                }
6686            } else {
6687                final PackageParser.Package pkg = mPackages.get(pkgName);
6688                result = null;
6689                if (pkg != null) {
6690                    result = filterIfNotSystemUser(
6691                            mActivities.queryIntentForPackage(
6692                                    intent, resolvedType, flags, pkg.activities, userId),
6693                            userId);
6694                }
6695                if (result == null || result.size() == 0) {
6696                    // the caller wants to resolve for a particular package; however, there
6697                    // were no installed results, so, try to find an ephemeral result
6698                    addInstant = isInstantAppResolutionAllowed(
6699                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6700                    if (result == null) {
6701                        result = new ArrayList<>();
6702                    }
6703                }
6704            }
6705        }
6706        if (addInstant) {
6707            result = maybeAddInstantAppInstaller(
6708                    result, intent, resolvedType, flags, userId, resolveForStart);
6709        }
6710        if (sortResult) {
6711            Collections.sort(result, mResolvePrioritySorter);
6712        }
6713        return applyPostResolutionFilter(
6714                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6715    }
6716
6717    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6718            String resolvedType, int flags, int userId, boolean resolveForStart) {
6719        // first, check to see if we've got an instant app already installed
6720        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6721        ResolveInfo localInstantApp = null;
6722        boolean blockResolution = false;
6723        if (!alreadyResolvedLocally) {
6724            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6725                    flags
6726                        | PackageManager.GET_RESOLVED_FILTER
6727                        | PackageManager.MATCH_INSTANT
6728                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6729                    userId);
6730            for (int i = instantApps.size() - 1; i >= 0; --i) {
6731                final ResolveInfo info = instantApps.get(i);
6732                final String packageName = info.activityInfo.packageName;
6733                final PackageSetting ps = mSettings.mPackages.get(packageName);
6734                if (ps.getInstantApp(userId)) {
6735                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6736                    final int status = (int)(packedStatus >> 32);
6737                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6738                        // there's a local instant application installed, but, the user has
6739                        // chosen to never use it; skip resolution and don't acknowledge
6740                        // an instant application is even available
6741                        if (DEBUG_INSTANT) {
6742                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6743                        }
6744                        blockResolution = true;
6745                        break;
6746                    } else {
6747                        // we have a locally installed instant application; skip resolution
6748                        // but acknowledge there's an instant application available
6749                        if (DEBUG_INSTANT) {
6750                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6751                        }
6752                        localInstantApp = info;
6753                        break;
6754                    }
6755                }
6756            }
6757        }
6758        // no app installed, let's see if one's available
6759        AuxiliaryResolveInfo auxiliaryResponse = null;
6760        if (!blockResolution) {
6761            if (localInstantApp == null) {
6762                // we don't have an instant app locally, resolve externally
6763                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6764                final InstantAppRequest requestObject = new InstantAppRequest(
6765                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6766                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6767                        resolveForStart);
6768                auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne(
6769                        mInstantAppResolverConnection, requestObject);
6770                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6771            } else {
6772                // we have an instant application locally, but, we can't admit that since
6773                // callers shouldn't be able to determine prior browsing. create a dummy
6774                // auxiliary response so the downstream code behaves as if there's an
6775                // instant application available externally. when it comes time to start
6776                // the instant application, we'll do the right thing.
6777                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6778                auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */,
6779                                        ai.packageName, ai.longVersionCode, null /* splitName */);
6780            }
6781        }
6782        if (intent.isWebIntent() && auxiliaryResponse == null) {
6783            return result;
6784        }
6785        final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6786        if (ps == null
6787                || ps.getUserState().get(userId) == null
6788                || !ps.getUserState().get(userId).isEnabled(mInstantAppInstallerActivity, 0)) {
6789            return result;
6790        }
6791        final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6792        ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6793                mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6794        ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6795                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6796        // add a non-generic filter
6797        ephemeralInstaller.filter = new IntentFilter();
6798        if (intent.getAction() != null) {
6799            ephemeralInstaller.filter.addAction(intent.getAction());
6800        }
6801        if (intent.getData() != null && intent.getData().getPath() != null) {
6802            ephemeralInstaller.filter.addDataPath(
6803                    intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6804        }
6805        ephemeralInstaller.isInstantAppAvailable = true;
6806        // make sure this resolver is the default
6807        ephemeralInstaller.isDefault = true;
6808        ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6809        if (DEBUG_INSTANT) {
6810            Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6811        }
6812
6813        result.add(ephemeralInstaller);
6814        return result;
6815    }
6816
6817    private static class CrossProfileDomainInfo {
6818        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6819        ResolveInfo resolveInfo;
6820        /* Best domain verification status of the activities found in the other profile */
6821        int bestDomainVerificationStatus;
6822    }
6823
6824    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6825            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6826        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6827                sourceUserId)) {
6828            return null;
6829        }
6830        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6831                resolvedType, flags, parentUserId);
6832
6833        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6834            return null;
6835        }
6836        CrossProfileDomainInfo result = null;
6837        int size = resultTargetUser.size();
6838        for (int i = 0; i < size; i++) {
6839            ResolveInfo riTargetUser = resultTargetUser.get(i);
6840            // Intent filter verification is only for filters that specify a host. So don't return
6841            // those that handle all web uris.
6842            if (riTargetUser.handleAllWebDataURI) {
6843                continue;
6844            }
6845            String packageName = riTargetUser.activityInfo.packageName;
6846            PackageSetting ps = mSettings.mPackages.get(packageName);
6847            if (ps == null) {
6848                continue;
6849            }
6850            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6851            int status = (int)(verificationState >> 32);
6852            if (result == null) {
6853                result = new CrossProfileDomainInfo();
6854                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6855                        sourceUserId, parentUserId);
6856                result.bestDomainVerificationStatus = status;
6857            } else {
6858                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6859                        result.bestDomainVerificationStatus);
6860            }
6861        }
6862        // Don't consider matches with status NEVER across profiles.
6863        if (result != null && result.bestDomainVerificationStatus
6864                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6865            return null;
6866        }
6867        return result;
6868    }
6869
6870    /**
6871     * Verification statuses are ordered from the worse to the best, except for
6872     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6873     */
6874    private int bestDomainVerificationStatus(int status1, int status2) {
6875        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6876            return status2;
6877        }
6878        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6879            return status1;
6880        }
6881        return (int) MathUtils.max(status1, status2);
6882    }
6883
6884    private boolean isUserEnabled(int userId) {
6885        long callingId = Binder.clearCallingIdentity();
6886        try {
6887            UserInfo userInfo = sUserManager.getUserInfo(userId);
6888            return userInfo != null && userInfo.isEnabled();
6889        } finally {
6890            Binder.restoreCallingIdentity(callingId);
6891        }
6892    }
6893
6894    /**
6895     * Filter out activities with systemUserOnly flag set, when current user is not System.
6896     *
6897     * @return filtered list
6898     */
6899    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6900        if (userId == UserHandle.USER_SYSTEM) {
6901            return resolveInfos;
6902        }
6903        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6904            ResolveInfo info = resolveInfos.get(i);
6905            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6906                resolveInfos.remove(i);
6907            }
6908        }
6909        return resolveInfos;
6910    }
6911
6912    /**
6913     * Filters out ephemeral activities.
6914     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6915     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6916     *
6917     * @param resolveInfos The pre-filtered list of resolved activities
6918     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6919     *          is performed.
6920     * @param intent
6921     * @return A filtered list of resolved activities.
6922     */
6923    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6924            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId,
6925            Intent intent) {
6926        final boolean blockInstant = intent.isWebIntent() && areWebInstantAppsDisabled();
6927        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6928            final ResolveInfo info = resolveInfos.get(i);
6929            // remove locally resolved instant app web results when disabled
6930            if (info.isInstantAppAvailable && blockInstant) {
6931                resolveInfos.remove(i);
6932                continue;
6933            }
6934            // allow activities that are defined in the provided package
6935            if (allowDynamicSplits
6936                    && info.activityInfo != null
6937                    && info.activityInfo.splitName != null
6938                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6939                            info.activityInfo.splitName)) {
6940                if (mInstantAppInstallerActivity == null) {
6941                    if (DEBUG_INSTALL) {
6942                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6943                    }
6944                    resolveInfos.remove(i);
6945                    continue;
6946                }
6947                if (blockInstant && isInstantApp(info.activityInfo.packageName, userId)) {
6948                    resolveInfos.remove(i);
6949                    continue;
6950                }
6951                // requested activity is defined in a split that hasn't been installed yet.
6952                // add the installer to the resolve list
6953                if (DEBUG_INSTALL) {
6954                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6955                }
6956                final ResolveInfo installerInfo = new ResolveInfo(
6957                        mInstantAppInstallerInfo);
6958                final ComponentName installFailureActivity = findInstallFailureActivity(
6959                        info.activityInfo.packageName,  filterCallingUid, userId);
6960                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6961                        installFailureActivity,
6962                        info.activityInfo.packageName,
6963                        info.activityInfo.applicationInfo.longVersionCode,
6964                        info.activityInfo.splitName);
6965                // add a non-generic filter
6966                installerInfo.filter = new IntentFilter();
6967
6968                // This resolve info may appear in the chooser UI, so let us make it
6969                // look as the one it replaces as far as the user is concerned which
6970                // requires loading the correct label and icon for the resolve info.
6971                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6972                installerInfo.labelRes = info.resolveLabelResId();
6973                installerInfo.icon = info.resolveIconResId();
6974                installerInfo.isInstantAppAvailable = true;
6975                resolveInfos.set(i, installerInfo);
6976                continue;
6977            }
6978            // caller is a full app, don't need to apply any other filtering
6979            if (ephemeralPkgName == null) {
6980                continue;
6981            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6982                // caller is same app; don't need to apply any other filtering
6983                continue;
6984            }
6985            // allow activities that have been explicitly exposed to ephemeral apps
6986            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6987            if (!isEphemeralApp
6988                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6989                continue;
6990            }
6991            resolveInfos.remove(i);
6992        }
6993        return resolveInfos;
6994    }
6995
6996    /**
6997     * Returns the activity component that can handle install failures.
6998     * <p>By default, the instant application installer handles failures. However, an
6999     * application may want to handle failures on its own. Applications do this by
7000     * creating an activity with an intent filter that handles the action
7001     * {@link Intent#ACTION_INSTALL_FAILURE}.
7002     */
7003    private @Nullable ComponentName findInstallFailureActivity(
7004            String packageName, int filterCallingUid, int userId) {
7005        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
7006        failureActivityIntent.setPackage(packageName);
7007        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
7008        final List<ResolveInfo> result = queryIntentActivitiesInternal(
7009                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
7010                false /*resolveForStart*/, false /*allowDynamicSplits*/);
7011        final int NR = result.size();
7012        if (NR > 0) {
7013            for (int i = 0; i < NR; i++) {
7014                final ResolveInfo info = result.get(i);
7015                if (info.activityInfo.splitName != null) {
7016                    continue;
7017                }
7018                return new ComponentName(packageName, info.activityInfo.name);
7019            }
7020        }
7021        return null;
7022    }
7023
7024    /**
7025     * @param resolveInfos list of resolve infos in descending priority order
7026     * @return if the list contains a resolve info with non-negative priority
7027     */
7028    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7029        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7030    }
7031
7032    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7033            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7034            int userId) {
7035        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7036
7037        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7038            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7039                    candidates.size());
7040        }
7041
7042        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7043        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7044        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7045        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7046        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7047        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7048
7049        synchronized (mPackages) {
7050            final int count = candidates.size();
7051            // First, try to use linked apps. Partition the candidates into four lists:
7052            // one for the final results, one for the "do not use ever", one for "undefined status"
7053            // and finally one for "browser app type".
7054            for (int n=0; n<count; n++) {
7055                ResolveInfo info = candidates.get(n);
7056                String packageName = info.activityInfo.packageName;
7057                PackageSetting ps = mSettings.mPackages.get(packageName);
7058                if (ps != null) {
7059                    // Add to the special match all list (Browser use case)
7060                    if (info.handleAllWebDataURI) {
7061                        matchAllList.add(info);
7062                        continue;
7063                    }
7064                    // Try to get the status from User settings first
7065                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7066                    int status = (int)(packedStatus >> 32);
7067                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7068                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7069                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7070                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7071                                    + " : linkgen=" + linkGeneration);
7072                        }
7073                        // Use link-enabled generation as preferredOrder, i.e.
7074                        // prefer newly-enabled over earlier-enabled.
7075                        info.preferredOrder = linkGeneration;
7076                        alwaysList.add(info);
7077                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7078                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7079                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7080                        }
7081                        neverList.add(info);
7082                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7083                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7084                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7085                        }
7086                        alwaysAskList.add(info);
7087                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7088                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7089                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7090                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7091                        }
7092                        undefinedList.add(info);
7093                    }
7094                }
7095            }
7096
7097            // We'll want to include browser possibilities in a few cases
7098            boolean includeBrowser = false;
7099
7100            // First try to add the "always" resolution(s) for the current user, if any
7101            if (alwaysList.size() > 0) {
7102                result.addAll(alwaysList);
7103            } else {
7104                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7105                result.addAll(undefinedList);
7106                // Maybe add one for the other profile.
7107                if (xpDomainInfo != null && (
7108                        xpDomainInfo.bestDomainVerificationStatus
7109                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7110                    result.add(xpDomainInfo.resolveInfo);
7111                }
7112                includeBrowser = true;
7113            }
7114
7115            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7116            // If there were 'always' entries their preferred order has been set, so we also
7117            // back that off to make the alternatives equivalent
7118            if (alwaysAskList.size() > 0) {
7119                for (ResolveInfo i : result) {
7120                    i.preferredOrder = 0;
7121                }
7122                result.addAll(alwaysAskList);
7123                includeBrowser = true;
7124            }
7125
7126            if (includeBrowser) {
7127                // Also add browsers (all of them or only the default one)
7128                if (DEBUG_DOMAIN_VERIFICATION) {
7129                    Slog.v(TAG, "   ...including browsers in candidate set");
7130                }
7131                if ((matchFlags & MATCH_ALL) != 0) {
7132                    result.addAll(matchAllList);
7133                } else {
7134                    // Browser/generic handling case.  If there's a default browser, go straight
7135                    // to that (but only if there is no other higher-priority match).
7136                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7137                    int maxMatchPrio = 0;
7138                    ResolveInfo defaultBrowserMatch = null;
7139                    final int numCandidates = matchAllList.size();
7140                    for (int n = 0; n < numCandidates; n++) {
7141                        ResolveInfo info = matchAllList.get(n);
7142                        // track the highest overall match priority...
7143                        if (info.priority > maxMatchPrio) {
7144                            maxMatchPrio = info.priority;
7145                        }
7146                        // ...and the highest-priority default browser match
7147                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7148                            if (defaultBrowserMatch == null
7149                                    || (defaultBrowserMatch.priority < info.priority)) {
7150                                if (debug) {
7151                                    Slog.v(TAG, "Considering default browser match " + info);
7152                                }
7153                                defaultBrowserMatch = info;
7154                            }
7155                        }
7156                    }
7157                    if (defaultBrowserMatch != null
7158                            && defaultBrowserMatch.priority >= maxMatchPrio
7159                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7160                    {
7161                        if (debug) {
7162                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7163                        }
7164                        result.add(defaultBrowserMatch);
7165                    } else {
7166                        result.addAll(matchAllList);
7167                    }
7168                }
7169
7170                // If there is nothing selected, add all candidates and remove the ones that the user
7171                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7172                if (result.size() == 0) {
7173                    result.addAll(candidates);
7174                    result.removeAll(neverList);
7175                }
7176            }
7177        }
7178        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7179            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7180                    result.size());
7181            for (ResolveInfo info : result) {
7182                Slog.v(TAG, "  + " + info.activityInfo);
7183            }
7184        }
7185        return result;
7186    }
7187
7188    // Returns a packed value as a long:
7189    //
7190    // high 'int'-sized word: link status: undefined/ask/never/always.
7191    // low 'int'-sized word: relative priority among 'always' results.
7192    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7193        long result = ps.getDomainVerificationStatusForUser(userId);
7194        // if none available, get the master status
7195        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7196            if (ps.getIntentFilterVerificationInfo() != null) {
7197                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7198            }
7199        }
7200        return result;
7201    }
7202
7203    private ResolveInfo querySkipCurrentProfileIntents(
7204            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7205            int flags, int sourceUserId) {
7206        if (matchingFilters != null) {
7207            int size = matchingFilters.size();
7208            for (int i = 0; i < size; i ++) {
7209                CrossProfileIntentFilter filter = matchingFilters.get(i);
7210                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7211                    // Checking if there are activities in the target user that can handle the
7212                    // intent.
7213                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7214                            resolvedType, flags, sourceUserId);
7215                    if (resolveInfo != null) {
7216                        return resolveInfo;
7217                    }
7218                }
7219            }
7220        }
7221        return null;
7222    }
7223
7224    // Return matching ResolveInfo in target user if any.
7225    private ResolveInfo queryCrossProfileIntents(
7226            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7227            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7228        if (matchingFilters != null) {
7229            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7230            // match the same intent. For performance reasons, it is better not to
7231            // run queryIntent twice for the same userId
7232            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7233            int size = matchingFilters.size();
7234            for (int i = 0; i < size; i++) {
7235                CrossProfileIntentFilter filter = matchingFilters.get(i);
7236                int targetUserId = filter.getTargetUserId();
7237                boolean skipCurrentProfile =
7238                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7239                boolean skipCurrentProfileIfNoMatchFound =
7240                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7241                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7242                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7243                    // Checking if there are activities in the target user that can handle the
7244                    // intent.
7245                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7246                            resolvedType, flags, sourceUserId);
7247                    if (resolveInfo != null) return resolveInfo;
7248                    alreadyTriedUserIds.put(targetUserId, true);
7249                }
7250            }
7251        }
7252        return null;
7253    }
7254
7255    /**
7256     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7257     * will forward the intent to the filter's target user.
7258     * Otherwise, returns null.
7259     */
7260    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7261            String resolvedType, int flags, int sourceUserId) {
7262        int targetUserId = filter.getTargetUserId();
7263        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7264                resolvedType, flags, targetUserId);
7265        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7266            // If all the matches in the target profile are suspended, return null.
7267            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7268                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7269                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7270                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7271                            targetUserId);
7272                }
7273            }
7274        }
7275        return null;
7276    }
7277
7278    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7279            int sourceUserId, int targetUserId) {
7280        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7281        long ident = Binder.clearCallingIdentity();
7282        boolean targetIsProfile;
7283        try {
7284            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7285        } finally {
7286            Binder.restoreCallingIdentity(ident);
7287        }
7288        String className;
7289        if (targetIsProfile) {
7290            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7291        } else {
7292            className = FORWARD_INTENT_TO_PARENT;
7293        }
7294        ComponentName forwardingActivityComponentName = new ComponentName(
7295                mAndroidApplication.packageName, className);
7296        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7297                sourceUserId);
7298        if (!targetIsProfile) {
7299            forwardingActivityInfo.showUserIcon = targetUserId;
7300            forwardingResolveInfo.noResourceId = true;
7301        }
7302        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7303        forwardingResolveInfo.priority = 0;
7304        forwardingResolveInfo.preferredOrder = 0;
7305        forwardingResolveInfo.match = 0;
7306        forwardingResolveInfo.isDefault = true;
7307        forwardingResolveInfo.filter = filter;
7308        forwardingResolveInfo.targetUserId = targetUserId;
7309        return forwardingResolveInfo;
7310    }
7311
7312    @Override
7313    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7314            Intent[] specifics, String[] specificTypes, Intent intent,
7315            String resolvedType, int flags, int userId) {
7316        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7317                specificTypes, intent, resolvedType, flags, userId));
7318    }
7319
7320    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7321            Intent[] specifics, String[] specificTypes, Intent intent,
7322            String resolvedType, int flags, int userId) {
7323        if (!sUserManager.exists(userId)) return Collections.emptyList();
7324        final int callingUid = Binder.getCallingUid();
7325        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7326                false /*includeInstantApps*/);
7327        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7328                false /*requireFullPermission*/, false /*checkShell*/,
7329                "query intent activity options");
7330        final String resultsAction = intent.getAction();
7331
7332        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7333                | PackageManager.GET_RESOLVED_FILTER, userId);
7334
7335        if (DEBUG_INTENT_MATCHING) {
7336            Log.v(TAG, "Query " + intent + ": " + results);
7337        }
7338
7339        int specificsPos = 0;
7340        int N;
7341
7342        // todo: note that the algorithm used here is O(N^2).  This
7343        // isn't a problem in our current environment, but if we start running
7344        // into situations where we have more than 5 or 10 matches then this
7345        // should probably be changed to something smarter...
7346
7347        // First we go through and resolve each of the specific items
7348        // that were supplied, taking care of removing any corresponding
7349        // duplicate items in the generic resolve list.
7350        if (specifics != null) {
7351            for (int i=0; i<specifics.length; i++) {
7352                final Intent sintent = specifics[i];
7353                if (sintent == null) {
7354                    continue;
7355                }
7356
7357                if (DEBUG_INTENT_MATCHING) {
7358                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7359                }
7360
7361                String action = sintent.getAction();
7362                if (resultsAction != null && resultsAction.equals(action)) {
7363                    // If this action was explicitly requested, then don't
7364                    // remove things that have it.
7365                    action = null;
7366                }
7367
7368                ResolveInfo ri = null;
7369                ActivityInfo ai = null;
7370
7371                ComponentName comp = sintent.getComponent();
7372                if (comp == null) {
7373                    ri = resolveIntent(
7374                        sintent,
7375                        specificTypes != null ? specificTypes[i] : null,
7376                            flags, userId);
7377                    if (ri == null) {
7378                        continue;
7379                    }
7380                    if (ri == mResolveInfo) {
7381                        // ACK!  Must do something better with this.
7382                    }
7383                    ai = ri.activityInfo;
7384                    comp = new ComponentName(ai.applicationInfo.packageName,
7385                            ai.name);
7386                } else {
7387                    ai = getActivityInfo(comp, flags, userId);
7388                    if (ai == null) {
7389                        continue;
7390                    }
7391                }
7392
7393                // Look for any generic query activities that are duplicates
7394                // of this specific one, and remove them from the results.
7395                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7396                N = results.size();
7397                int j;
7398                for (j=specificsPos; j<N; j++) {
7399                    ResolveInfo sri = results.get(j);
7400                    if ((sri.activityInfo.name.equals(comp.getClassName())
7401                            && sri.activityInfo.applicationInfo.packageName.equals(
7402                                    comp.getPackageName()))
7403                        || (action != null && sri.filter.matchAction(action))) {
7404                        results.remove(j);
7405                        if (DEBUG_INTENT_MATCHING) Log.v(
7406                            TAG, "Removing duplicate item from " + j
7407                            + " due to specific " + specificsPos);
7408                        if (ri == null) {
7409                            ri = sri;
7410                        }
7411                        j--;
7412                        N--;
7413                    }
7414                }
7415
7416                // Add this specific item to its proper place.
7417                if (ri == null) {
7418                    ri = new ResolveInfo();
7419                    ri.activityInfo = ai;
7420                }
7421                results.add(specificsPos, ri);
7422                ri.specificIndex = i;
7423                specificsPos++;
7424            }
7425        }
7426
7427        // Now we go through the remaining generic results and remove any
7428        // duplicate actions that are found here.
7429        N = results.size();
7430        for (int i=specificsPos; i<N-1; i++) {
7431            final ResolveInfo rii = results.get(i);
7432            if (rii.filter == null) {
7433                continue;
7434            }
7435
7436            // Iterate over all of the actions of this result's intent
7437            // filter...  typically this should be just one.
7438            final Iterator<String> it = rii.filter.actionsIterator();
7439            if (it == null) {
7440                continue;
7441            }
7442            while (it.hasNext()) {
7443                final String action = it.next();
7444                if (resultsAction != null && resultsAction.equals(action)) {
7445                    // If this action was explicitly requested, then don't
7446                    // remove things that have it.
7447                    continue;
7448                }
7449                for (int j=i+1; j<N; j++) {
7450                    final ResolveInfo rij = results.get(j);
7451                    if (rij.filter != null && rij.filter.hasAction(action)) {
7452                        results.remove(j);
7453                        if (DEBUG_INTENT_MATCHING) Log.v(
7454                            TAG, "Removing duplicate item from " + j
7455                            + " due to action " + action + " at " + i);
7456                        j--;
7457                        N--;
7458                    }
7459                }
7460            }
7461
7462            // If the caller didn't request filter information, drop it now
7463            // so we don't have to marshall/unmarshall it.
7464            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7465                rii.filter = null;
7466            }
7467        }
7468
7469        // Filter out the caller activity if so requested.
7470        if (caller != null) {
7471            N = results.size();
7472            for (int i=0; i<N; i++) {
7473                ActivityInfo ainfo = results.get(i).activityInfo;
7474                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7475                        && caller.getClassName().equals(ainfo.name)) {
7476                    results.remove(i);
7477                    break;
7478                }
7479            }
7480        }
7481
7482        // If the caller didn't request filter information,
7483        // drop them now so we don't have to
7484        // marshall/unmarshall it.
7485        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7486            N = results.size();
7487            for (int i=0; i<N; i++) {
7488                results.get(i).filter = null;
7489            }
7490        }
7491
7492        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7493        return results;
7494    }
7495
7496    @Override
7497    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7498            String resolvedType, int flags, int userId) {
7499        return new ParceledListSlice<>(
7500                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7501                        false /*allowDynamicSplits*/));
7502    }
7503
7504    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7505            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7506        if (!sUserManager.exists(userId)) return Collections.emptyList();
7507        final int callingUid = Binder.getCallingUid();
7508        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7509                false /*requireFullPermission*/, false /*checkShell*/,
7510                "query intent receivers");
7511        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7512        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7513                false /*includeInstantApps*/);
7514        ComponentName comp = intent.getComponent();
7515        if (comp == null) {
7516            if (intent.getSelector() != null) {
7517                intent = intent.getSelector();
7518                comp = intent.getComponent();
7519            }
7520        }
7521        if (comp != null) {
7522            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7523            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7524            if (ai != null) {
7525                // When specifying an explicit component, we prevent the activity from being
7526                // used when either 1) the calling package is normal and the activity is within
7527                // an instant application or 2) the calling package is ephemeral and the
7528                // activity is not visible to instant applications.
7529                final boolean matchInstantApp =
7530                        (flags & PackageManager.MATCH_INSTANT) != 0;
7531                final boolean matchVisibleToInstantAppOnly =
7532                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7533                final boolean matchExplicitlyVisibleOnly =
7534                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7535                final boolean isCallerInstantApp =
7536                        instantAppPkgName != null;
7537                final boolean isTargetSameInstantApp =
7538                        comp.getPackageName().equals(instantAppPkgName);
7539                final boolean isTargetInstantApp =
7540                        (ai.applicationInfo.privateFlags
7541                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7542                final boolean isTargetVisibleToInstantApp =
7543                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7544                final boolean isTargetExplicitlyVisibleToInstantApp =
7545                        isTargetVisibleToInstantApp
7546                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7547                final boolean isTargetHiddenFromInstantApp =
7548                        !isTargetVisibleToInstantApp
7549                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7550                final boolean blockResolution =
7551                        !isTargetSameInstantApp
7552                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7553                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7554                                        && isTargetHiddenFromInstantApp));
7555                if (!blockResolution) {
7556                    ResolveInfo ri = new ResolveInfo();
7557                    ri.activityInfo = ai;
7558                    list.add(ri);
7559                }
7560            }
7561            return applyPostResolutionFilter(
7562                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7563        }
7564
7565        // reader
7566        synchronized (mPackages) {
7567            String pkgName = intent.getPackage();
7568            if (pkgName == null) {
7569                final List<ResolveInfo> result =
7570                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7571                return applyPostResolutionFilter(
7572                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7573            }
7574            final PackageParser.Package pkg = mPackages.get(pkgName);
7575            if (pkg != null) {
7576                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7577                        intent, resolvedType, flags, pkg.receivers, userId);
7578                return applyPostResolutionFilter(
7579                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7580            }
7581            return Collections.emptyList();
7582        }
7583    }
7584
7585    @Override
7586    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7587        final int callingUid = Binder.getCallingUid();
7588        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7589    }
7590
7591    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7592            int userId, int callingUid) {
7593        if (!sUserManager.exists(userId)) return null;
7594        flags = updateFlagsForResolve(
7595                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7596        List<ResolveInfo> query = queryIntentServicesInternal(
7597                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7598        if (query != null) {
7599            if (query.size() >= 1) {
7600                // If there is more than one service with the same priority,
7601                // just arbitrarily pick the first one.
7602                return query.get(0);
7603            }
7604        }
7605        return null;
7606    }
7607
7608    @Override
7609    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7610            String resolvedType, int flags, int userId) {
7611        final int callingUid = Binder.getCallingUid();
7612        return new ParceledListSlice<>(queryIntentServicesInternal(
7613                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7614    }
7615
7616    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7617            String resolvedType, int flags, int userId, int callingUid,
7618            boolean includeInstantApps) {
7619        if (!sUserManager.exists(userId)) return Collections.emptyList();
7620        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7621                false /*requireFullPermission*/, false /*checkShell*/,
7622                "query intent receivers");
7623        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7624        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7625        ComponentName comp = intent.getComponent();
7626        if (comp == null) {
7627            if (intent.getSelector() != null) {
7628                intent = intent.getSelector();
7629                comp = intent.getComponent();
7630            }
7631        }
7632        if (comp != null) {
7633            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7634            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7635            if (si != null) {
7636                // When specifying an explicit component, we prevent the service from being
7637                // used when either 1) the service is in an instant application and the
7638                // caller is not the same instant application or 2) the calling package is
7639                // ephemeral and the activity is not visible to ephemeral applications.
7640                final boolean matchInstantApp =
7641                        (flags & PackageManager.MATCH_INSTANT) != 0;
7642                final boolean matchVisibleToInstantAppOnly =
7643                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7644                final boolean isCallerInstantApp =
7645                        instantAppPkgName != null;
7646                final boolean isTargetSameInstantApp =
7647                        comp.getPackageName().equals(instantAppPkgName);
7648                final boolean isTargetInstantApp =
7649                        (si.applicationInfo.privateFlags
7650                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7651                final boolean isTargetHiddenFromInstantApp =
7652                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7653                final boolean blockResolution =
7654                        !isTargetSameInstantApp
7655                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7656                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7657                                        && isTargetHiddenFromInstantApp));
7658                if (!blockResolution) {
7659                    final ResolveInfo ri = new ResolveInfo();
7660                    ri.serviceInfo = si;
7661                    list.add(ri);
7662                }
7663            }
7664            return list;
7665        }
7666
7667        // reader
7668        synchronized (mPackages) {
7669            String pkgName = intent.getPackage();
7670            if (pkgName == null) {
7671                return applyPostServiceResolutionFilter(
7672                        mServices.queryIntent(intent, resolvedType, flags, userId),
7673                        instantAppPkgName);
7674            }
7675            final PackageParser.Package pkg = mPackages.get(pkgName);
7676            if (pkg != null) {
7677                return applyPostServiceResolutionFilter(
7678                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7679                                userId),
7680                        instantAppPkgName);
7681            }
7682            return Collections.emptyList();
7683        }
7684    }
7685
7686    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7687            String instantAppPkgName) {
7688        if (instantAppPkgName == null) {
7689            return resolveInfos;
7690        }
7691        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7692            final ResolveInfo info = resolveInfos.get(i);
7693            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7694            // allow services that are defined in the provided package
7695            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7696                if (info.serviceInfo.splitName != null
7697                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7698                                info.serviceInfo.splitName)) {
7699                    // requested service is defined in a split that hasn't been installed yet.
7700                    // add the installer to the resolve list
7701                    if (DEBUG_INSTANT) {
7702                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7703                    }
7704                    final ResolveInfo installerInfo = new ResolveInfo(
7705                            mInstantAppInstallerInfo);
7706                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7707                            null /* installFailureActivity */,
7708                            info.serviceInfo.packageName,
7709                            info.serviceInfo.applicationInfo.longVersionCode,
7710                            info.serviceInfo.splitName);
7711                    // add a non-generic filter
7712                    installerInfo.filter = new IntentFilter();
7713                    // load resources from the correct package
7714                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7715                    resolveInfos.set(i, installerInfo);
7716                }
7717                continue;
7718            }
7719            // allow services that have been explicitly exposed to ephemeral apps
7720            if (!isEphemeralApp
7721                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7722                continue;
7723            }
7724            resolveInfos.remove(i);
7725        }
7726        return resolveInfos;
7727    }
7728
7729    @Override
7730    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7731            String resolvedType, int flags, int userId) {
7732        return new ParceledListSlice<>(
7733                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7734    }
7735
7736    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7737            Intent intent, String resolvedType, int flags, int userId) {
7738        if (!sUserManager.exists(userId)) return Collections.emptyList();
7739        final int callingUid = Binder.getCallingUid();
7740        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7741        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7742                false /*includeInstantApps*/);
7743        ComponentName comp = intent.getComponent();
7744        if (comp == null) {
7745            if (intent.getSelector() != null) {
7746                intent = intent.getSelector();
7747                comp = intent.getComponent();
7748            }
7749        }
7750        if (comp != null) {
7751            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7752            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7753            if (pi != null) {
7754                // When specifying an explicit component, we prevent the provider from being
7755                // used when either 1) the provider is in an instant application and the
7756                // caller is not the same instant application or 2) the calling package is an
7757                // instant application and the provider is not visible to instant applications.
7758                final boolean matchInstantApp =
7759                        (flags & PackageManager.MATCH_INSTANT) != 0;
7760                final boolean matchVisibleToInstantAppOnly =
7761                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7762                final boolean isCallerInstantApp =
7763                        instantAppPkgName != null;
7764                final boolean isTargetSameInstantApp =
7765                        comp.getPackageName().equals(instantAppPkgName);
7766                final boolean isTargetInstantApp =
7767                        (pi.applicationInfo.privateFlags
7768                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7769                final boolean isTargetHiddenFromInstantApp =
7770                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7771                final boolean blockResolution =
7772                        !isTargetSameInstantApp
7773                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7774                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7775                                        && isTargetHiddenFromInstantApp));
7776                if (!blockResolution) {
7777                    final ResolveInfo ri = new ResolveInfo();
7778                    ri.providerInfo = pi;
7779                    list.add(ri);
7780                }
7781            }
7782            return list;
7783        }
7784
7785        // reader
7786        synchronized (mPackages) {
7787            String pkgName = intent.getPackage();
7788            if (pkgName == null) {
7789                return applyPostContentProviderResolutionFilter(
7790                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7791                        instantAppPkgName);
7792            }
7793            final PackageParser.Package pkg = mPackages.get(pkgName);
7794            if (pkg != null) {
7795                return applyPostContentProviderResolutionFilter(
7796                        mProviders.queryIntentForPackage(
7797                        intent, resolvedType, flags, pkg.providers, userId),
7798                        instantAppPkgName);
7799            }
7800            return Collections.emptyList();
7801        }
7802    }
7803
7804    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7805            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7806        if (instantAppPkgName == null) {
7807            return resolveInfos;
7808        }
7809        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7810            final ResolveInfo info = resolveInfos.get(i);
7811            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7812            // allow providers that are defined in the provided package
7813            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7814                if (info.providerInfo.splitName != null
7815                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7816                                info.providerInfo.splitName)) {
7817                    // requested provider is defined in a split that hasn't been installed yet.
7818                    // add the installer to the resolve list
7819                    if (DEBUG_INSTANT) {
7820                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7821                    }
7822                    final ResolveInfo installerInfo = new ResolveInfo(
7823                            mInstantAppInstallerInfo);
7824                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7825                            null /*failureActivity*/,
7826                            info.providerInfo.packageName,
7827                            info.providerInfo.applicationInfo.longVersionCode,
7828                            info.providerInfo.splitName);
7829                    // add a non-generic filter
7830                    installerInfo.filter = new IntentFilter();
7831                    // load resources from the correct package
7832                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7833                    resolveInfos.set(i, installerInfo);
7834                }
7835                continue;
7836            }
7837            // allow providers that have been explicitly exposed to instant applications
7838            if (!isEphemeralApp
7839                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7840                continue;
7841            }
7842            resolveInfos.remove(i);
7843        }
7844        return resolveInfos;
7845    }
7846
7847    @Override
7848    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7849        final int callingUid = Binder.getCallingUid();
7850        if (getInstantAppPackageName(callingUid) != null) {
7851            return ParceledListSlice.emptyList();
7852        }
7853        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7854        flags = updateFlagsForPackage(flags, userId, null);
7855        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7856        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7857                true /* requireFullPermission */, false /* checkShell */,
7858                "get installed packages");
7859
7860        // writer
7861        synchronized (mPackages) {
7862            ArrayList<PackageInfo> list;
7863            if (listUninstalled) {
7864                list = new ArrayList<>(mSettings.mPackages.size());
7865                for (PackageSetting ps : mSettings.mPackages.values()) {
7866                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7867                        continue;
7868                    }
7869                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7870                        continue;
7871                    }
7872                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7873                    if (pi != null) {
7874                        list.add(pi);
7875                    }
7876                }
7877            } else {
7878                list = new ArrayList<>(mPackages.size());
7879                for (PackageParser.Package p : mPackages.values()) {
7880                    final PackageSetting ps = (PackageSetting) p.mExtras;
7881                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7882                        continue;
7883                    }
7884                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7885                        continue;
7886                    }
7887                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7888                            p.mExtras, flags, userId);
7889                    if (pi != null) {
7890                        list.add(pi);
7891                    }
7892                }
7893            }
7894
7895            return new ParceledListSlice<>(list);
7896        }
7897    }
7898
7899    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7900            String[] permissions, boolean[] tmp, int flags, int userId) {
7901        int numMatch = 0;
7902        final PermissionsState permissionsState = ps.getPermissionsState();
7903        for (int i=0; i<permissions.length; i++) {
7904            final String permission = permissions[i];
7905            if (permissionsState.hasPermission(permission, userId)) {
7906                tmp[i] = true;
7907                numMatch++;
7908            } else {
7909                tmp[i] = false;
7910            }
7911        }
7912        if (numMatch == 0) {
7913            return;
7914        }
7915        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7916
7917        // The above might return null in cases of uninstalled apps or install-state
7918        // skew across users/profiles.
7919        if (pi != null) {
7920            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7921                if (numMatch == permissions.length) {
7922                    pi.requestedPermissions = permissions;
7923                } else {
7924                    pi.requestedPermissions = new String[numMatch];
7925                    numMatch = 0;
7926                    for (int i=0; i<permissions.length; i++) {
7927                        if (tmp[i]) {
7928                            pi.requestedPermissions[numMatch] = permissions[i];
7929                            numMatch++;
7930                        }
7931                    }
7932                }
7933            }
7934            list.add(pi);
7935        }
7936    }
7937
7938    @Override
7939    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7940            String[] permissions, int flags, int userId) {
7941        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7942        flags = updateFlagsForPackage(flags, userId, permissions);
7943        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7944                true /* requireFullPermission */, false /* checkShell */,
7945                "get packages holding permissions");
7946        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7947
7948        // writer
7949        synchronized (mPackages) {
7950            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7951            boolean[] tmpBools = new boolean[permissions.length];
7952            if (listUninstalled) {
7953                for (PackageSetting ps : mSettings.mPackages.values()) {
7954                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7955                            userId);
7956                }
7957            } else {
7958                for (PackageParser.Package pkg : mPackages.values()) {
7959                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7960                    if (ps != null) {
7961                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7962                                userId);
7963                    }
7964                }
7965            }
7966
7967            return new ParceledListSlice<PackageInfo>(list);
7968        }
7969    }
7970
7971    @Override
7972    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7973        final int callingUid = Binder.getCallingUid();
7974        if (getInstantAppPackageName(callingUid) != null) {
7975            return ParceledListSlice.emptyList();
7976        }
7977        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7978        flags = updateFlagsForApplication(flags, userId, null);
7979        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7980
7981        // writer
7982        synchronized (mPackages) {
7983            ArrayList<ApplicationInfo> list;
7984            if (listUninstalled) {
7985                list = new ArrayList<>(mSettings.mPackages.size());
7986                for (PackageSetting ps : mSettings.mPackages.values()) {
7987                    ApplicationInfo ai;
7988                    int effectiveFlags = flags;
7989                    if (ps.isSystem()) {
7990                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7991                    }
7992                    if (ps.pkg != null) {
7993                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7994                            continue;
7995                        }
7996                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7997                            continue;
7998                        }
7999                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8000                                ps.readUserState(userId), userId);
8001                        if (ai != null) {
8002                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8003                        }
8004                    } else {
8005                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8006                        // and already converts to externally visible package name
8007                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8008                                callingUid, effectiveFlags, userId);
8009                    }
8010                    if (ai != null) {
8011                        list.add(ai);
8012                    }
8013                }
8014            } else {
8015                list = new ArrayList<>(mPackages.size());
8016                for (PackageParser.Package p : mPackages.values()) {
8017                    if (p.mExtras != null) {
8018                        PackageSetting ps = (PackageSetting) p.mExtras;
8019                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8020                            continue;
8021                        }
8022                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8023                            continue;
8024                        }
8025                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8026                                ps.readUserState(userId), userId);
8027                        if (ai != null) {
8028                            ai.packageName = resolveExternalPackageNameLPr(p);
8029                            list.add(ai);
8030                        }
8031                    }
8032                }
8033            }
8034
8035            return new ParceledListSlice<>(list);
8036        }
8037    }
8038
8039    @Override
8040    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8041        if (HIDE_EPHEMERAL_APIS) {
8042            return null;
8043        }
8044        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8045            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8046                    "getEphemeralApplications");
8047        }
8048        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8049                true /* requireFullPermission */, false /* checkShell */,
8050                "getEphemeralApplications");
8051        synchronized (mPackages) {
8052            List<InstantAppInfo> instantApps = mInstantAppRegistry
8053                    .getInstantAppsLPr(userId);
8054            if (instantApps != null) {
8055                return new ParceledListSlice<>(instantApps);
8056            }
8057        }
8058        return null;
8059    }
8060
8061    @Override
8062    public boolean isInstantApp(String packageName, int userId) {
8063        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8064                true /* requireFullPermission */, false /* checkShell */,
8065                "isInstantApp");
8066        if (HIDE_EPHEMERAL_APIS) {
8067            return false;
8068        }
8069
8070        synchronized (mPackages) {
8071            int callingUid = Binder.getCallingUid();
8072            if (Process.isIsolated(callingUid)) {
8073                callingUid = mIsolatedOwners.get(callingUid);
8074            }
8075            final PackageSetting ps = mSettings.mPackages.get(packageName);
8076            PackageParser.Package pkg = mPackages.get(packageName);
8077            final boolean returnAllowed =
8078                    ps != null
8079                    && (isCallerSameApp(packageName, callingUid)
8080                            || canViewInstantApps(callingUid, userId)
8081                            || mInstantAppRegistry.isInstantAccessGranted(
8082                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8083            if (returnAllowed) {
8084                return ps.getInstantApp(userId);
8085            }
8086        }
8087        return false;
8088    }
8089
8090    @Override
8091    public byte[] getInstantAppCookie(String packageName, int userId) {
8092        if (HIDE_EPHEMERAL_APIS) {
8093            return null;
8094        }
8095
8096        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8097                true /* requireFullPermission */, false /* checkShell */,
8098                "getInstantAppCookie");
8099        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8100            return null;
8101        }
8102        synchronized (mPackages) {
8103            return mInstantAppRegistry.getInstantAppCookieLPw(
8104                    packageName, userId);
8105        }
8106    }
8107
8108    @Override
8109    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8110        if (HIDE_EPHEMERAL_APIS) {
8111            return true;
8112        }
8113
8114        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8115                true /* requireFullPermission */, true /* checkShell */,
8116                "setInstantAppCookie");
8117        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8118            return false;
8119        }
8120        synchronized (mPackages) {
8121            return mInstantAppRegistry.setInstantAppCookieLPw(
8122                    packageName, cookie, userId);
8123        }
8124    }
8125
8126    @Override
8127    public Bitmap getInstantAppIcon(String packageName, int userId) {
8128        if (HIDE_EPHEMERAL_APIS) {
8129            return null;
8130        }
8131
8132        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8133            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8134                    "getInstantAppIcon");
8135        }
8136        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8137                true /* requireFullPermission */, false /* checkShell */,
8138                "getInstantAppIcon");
8139
8140        synchronized (mPackages) {
8141            return mInstantAppRegistry.getInstantAppIconLPw(
8142                    packageName, userId);
8143        }
8144    }
8145
8146    private boolean isCallerSameApp(String packageName, int uid) {
8147        PackageParser.Package pkg = mPackages.get(packageName);
8148        return pkg != null
8149                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8150    }
8151
8152    @Override
8153    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8154        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8155            return ParceledListSlice.emptyList();
8156        }
8157        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8158    }
8159
8160    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8161        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8162
8163        // reader
8164        synchronized (mPackages) {
8165            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8166            final int userId = UserHandle.getCallingUserId();
8167            while (i.hasNext()) {
8168                final PackageParser.Package p = i.next();
8169                if (p.applicationInfo == null) continue;
8170
8171                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8172                        && !p.applicationInfo.isDirectBootAware();
8173                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8174                        && p.applicationInfo.isDirectBootAware();
8175
8176                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8177                        && (!mSafeMode || isSystemApp(p))
8178                        && (matchesUnaware || matchesAware)) {
8179                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8180                    if (ps != null) {
8181                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8182                                ps.readUserState(userId), userId);
8183                        if (ai != null) {
8184                            finalList.add(ai);
8185                        }
8186                    }
8187                }
8188            }
8189        }
8190
8191        return finalList;
8192    }
8193
8194    @Override
8195    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8196        return resolveContentProviderInternal(name, flags, userId);
8197    }
8198
8199    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8200        if (!sUserManager.exists(userId)) return null;
8201        flags = updateFlagsForComponent(flags, userId, name);
8202        final int callingUid = Binder.getCallingUid();
8203        synchronized (mPackages) {
8204            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8205            PackageSetting ps = provider != null
8206                    ? mSettings.mPackages.get(provider.owner.packageName)
8207                    : null;
8208            if (ps != null) {
8209                // provider not enabled
8210                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8211                    return null;
8212                }
8213                final ComponentName component =
8214                        new ComponentName(provider.info.packageName, provider.info.name);
8215                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8216                    return null;
8217                }
8218                return PackageParser.generateProviderInfo(
8219                        provider, flags, ps.readUserState(userId), userId);
8220            }
8221            return null;
8222        }
8223    }
8224
8225    /**
8226     * @deprecated
8227     */
8228    @Deprecated
8229    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8230        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8231            return;
8232        }
8233        // reader
8234        synchronized (mPackages) {
8235            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8236                    .entrySet().iterator();
8237            final int userId = UserHandle.getCallingUserId();
8238            while (i.hasNext()) {
8239                Map.Entry<String, PackageParser.Provider> entry = i.next();
8240                PackageParser.Provider p = entry.getValue();
8241                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8242
8243                if (ps != null && p.syncable
8244                        && (!mSafeMode || (p.info.applicationInfo.flags
8245                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8246                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8247                            ps.readUserState(userId), userId);
8248                    if (info != null) {
8249                        outNames.add(entry.getKey());
8250                        outInfo.add(info);
8251                    }
8252                }
8253            }
8254        }
8255    }
8256
8257    @Override
8258    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8259            int uid, int flags, String metaDataKey) {
8260        final int callingUid = Binder.getCallingUid();
8261        final int userId = processName != null ? UserHandle.getUserId(uid)
8262                : UserHandle.getCallingUserId();
8263        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8264        flags = updateFlagsForComponent(flags, userId, processName);
8265        ArrayList<ProviderInfo> finalList = null;
8266        // reader
8267        synchronized (mPackages) {
8268            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8269            while (i.hasNext()) {
8270                final PackageParser.Provider p = i.next();
8271                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8272                if (ps != null && p.info.authority != null
8273                        && (processName == null
8274                                || (p.info.processName.equals(processName)
8275                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8276                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8277
8278                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8279                    // parameter.
8280                    if (metaDataKey != null
8281                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8282                        continue;
8283                    }
8284                    final ComponentName component =
8285                            new ComponentName(p.info.packageName, p.info.name);
8286                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8287                        continue;
8288                    }
8289                    if (finalList == null) {
8290                        finalList = new ArrayList<ProviderInfo>(3);
8291                    }
8292                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8293                            ps.readUserState(userId), userId);
8294                    if (info != null) {
8295                        finalList.add(info);
8296                    }
8297                }
8298            }
8299        }
8300
8301        if (finalList != null) {
8302            Collections.sort(finalList, mProviderInitOrderSorter);
8303            return new ParceledListSlice<ProviderInfo>(finalList);
8304        }
8305
8306        return ParceledListSlice.emptyList();
8307    }
8308
8309    @Override
8310    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8311        // reader
8312        synchronized (mPackages) {
8313            final int callingUid = Binder.getCallingUid();
8314            final int callingUserId = UserHandle.getUserId(callingUid);
8315            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8316            if (ps == null) return null;
8317            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8318                return null;
8319            }
8320            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8321            return PackageParser.generateInstrumentationInfo(i, flags);
8322        }
8323    }
8324
8325    @Override
8326    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8327            String targetPackage, int flags) {
8328        final int callingUid = Binder.getCallingUid();
8329        final int callingUserId = UserHandle.getUserId(callingUid);
8330        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8331        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8332            return ParceledListSlice.emptyList();
8333        }
8334        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8335    }
8336
8337    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8338            int flags) {
8339        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8340
8341        // reader
8342        synchronized (mPackages) {
8343            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8344            while (i.hasNext()) {
8345                final PackageParser.Instrumentation p = i.next();
8346                if (targetPackage == null
8347                        || targetPackage.equals(p.info.targetPackage)) {
8348                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8349                            flags);
8350                    if (ii != null) {
8351                        finalList.add(ii);
8352                    }
8353                }
8354            }
8355        }
8356
8357        return finalList;
8358    }
8359
8360    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8361        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8362        try {
8363            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8364        } finally {
8365            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8366        }
8367    }
8368
8369    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8370        final File[] files = scanDir.listFiles();
8371        if (ArrayUtils.isEmpty(files)) {
8372            Log.d(TAG, "No files in app dir " + scanDir);
8373            return;
8374        }
8375
8376        if (DEBUG_PACKAGE_SCANNING) {
8377            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8378                    + " flags=0x" + Integer.toHexString(parseFlags));
8379        }
8380        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8381                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8382                mParallelPackageParserCallback)) {
8383            // Submit files for parsing in parallel
8384            int fileCount = 0;
8385            for (File file : files) {
8386                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8387                        && !PackageInstallerService.isStageName(file.getName());
8388                if (!isPackage) {
8389                    // Ignore entries which are not packages
8390                    continue;
8391                }
8392                parallelPackageParser.submit(file, parseFlags);
8393                fileCount++;
8394            }
8395
8396            // Process results one by one
8397            for (; fileCount > 0; fileCount--) {
8398                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8399                Throwable throwable = parseResult.throwable;
8400                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8401
8402                if (throwable == null) {
8403                    // TODO(toddke): move lower in the scan chain
8404                    // Static shared libraries have synthetic package names
8405                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8406                        renameStaticSharedLibraryPackage(parseResult.pkg);
8407                    }
8408                    try {
8409                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8410                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8411                                    currentTime, null);
8412                        }
8413                    } catch (PackageManagerException e) {
8414                        errorCode = e.error;
8415                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8416                    }
8417                } else if (throwable instanceof PackageParser.PackageParserException) {
8418                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8419                            throwable;
8420                    errorCode = e.error;
8421                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8422                } else {
8423                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8424                            + parseResult.scanFile, throwable);
8425                }
8426
8427                // Delete invalid userdata apps
8428                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8429                        errorCode != PackageManager.INSTALL_SUCCEEDED) {
8430                    logCriticalInfo(Log.WARN,
8431                            "Deleting invalid package at " + parseResult.scanFile);
8432                    removeCodePathLI(parseResult.scanFile);
8433                }
8434            }
8435        }
8436    }
8437
8438    public static void reportSettingsProblem(int priority, String msg) {
8439        logCriticalInfo(priority, msg);
8440    }
8441
8442    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8443            boolean forceCollect, boolean skipVerify) throws PackageManagerException {
8444        // When upgrading from pre-N MR1, verify the package time stamp using the package
8445        // directory and not the APK file.
8446        final long lastModifiedTime = mIsPreNMR1Upgrade
8447                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8448        if (ps != null && !forceCollect
8449                && ps.codePathString.equals(pkg.codePath)
8450                && ps.timeStamp == lastModifiedTime
8451                && !isCompatSignatureUpdateNeeded(pkg)
8452                && !isRecoverSignatureUpdateNeeded(pkg)) {
8453            if (ps.signatures.mSigningDetails.signatures != null
8454                    && ps.signatures.mSigningDetails.signatures.length != 0
8455                    && ps.signatures.mSigningDetails.signatureSchemeVersion
8456                            != SignatureSchemeVersion.UNKNOWN) {
8457                // Optimization: reuse the existing cached signing data
8458                // if the package appears to be unchanged.
8459                pkg.mSigningDetails =
8460                        new PackageParser.SigningDetails(ps.signatures.mSigningDetails);
8461                return;
8462            }
8463
8464            Slog.w(TAG, "PackageSetting for " + ps.name
8465                    + " is missing signatures.  Collecting certs again to recover them.");
8466        } else {
8467            Slog.i(TAG, pkg.codePath + " changed; collecting certs" +
8468                    (forceCollect ? " (forced)" : ""));
8469        }
8470
8471        try {
8472            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8473            PackageParser.collectCertificates(pkg, skipVerify);
8474        } catch (PackageParserException e) {
8475            throw PackageManagerException.from(e);
8476        } finally {
8477            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8478        }
8479    }
8480
8481    /**
8482     * Clear the package profile if this was an upgrade and the package
8483     * version was updated.
8484     */
8485    private void maybeClearProfilesForUpgradesLI(
8486            @Nullable PackageSetting originalPkgSetting,
8487            @NonNull PackageParser.Package currentPkg) {
8488        if (originalPkgSetting == null || !isUpgrade()) {
8489          return;
8490        }
8491        if (originalPkgSetting.versionCode == currentPkg.mVersionCode) {
8492          return;
8493        }
8494
8495        clearAppProfilesLIF(currentPkg, UserHandle.USER_ALL);
8496        if (DEBUG_INSTALL) {
8497            Slog.d(TAG, originalPkgSetting.name
8498                  + " clear profile due to version change "
8499                  + originalPkgSetting.versionCode + " != "
8500                  + currentPkg.mVersionCode);
8501        }
8502    }
8503
8504    /**
8505     *  Traces a package scan.
8506     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8507     */
8508    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8509            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8510        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8511        try {
8512            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8513        } finally {
8514            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8515        }
8516    }
8517
8518    /**
8519     *  Scans a package and returns the newly parsed package.
8520     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8521     */
8522    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8523            long currentTime, UserHandle user) throws PackageManagerException {
8524        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8525        PackageParser pp = new PackageParser();
8526        pp.setSeparateProcesses(mSeparateProcesses);
8527        pp.setOnlyCoreApps(mOnlyCore);
8528        pp.setDisplayMetrics(mMetrics);
8529        pp.setCallback(mPackageParserCallback);
8530
8531        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8532        final PackageParser.Package pkg;
8533        try {
8534            pkg = pp.parsePackage(scanFile, parseFlags);
8535        } catch (PackageParserException e) {
8536            throw PackageManagerException.from(e);
8537        } finally {
8538            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8539        }
8540
8541        // Static shared libraries have synthetic package names
8542        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8543            renameStaticSharedLibraryPackage(pkg);
8544        }
8545
8546        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8547    }
8548
8549    /**
8550     *  Scans a package and returns the newly parsed package.
8551     *  @throws PackageManagerException on a parse error.
8552     */
8553    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8554            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8555            @Nullable UserHandle user)
8556                    throws PackageManagerException {
8557        // If the package has children and this is the first dive in the function
8558        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8559        // packages (parent and children) would be successfully scanned before the
8560        // actual scan since scanning mutates internal state and we want to atomically
8561        // install the package and its children.
8562        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8563            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8564                scanFlags |= SCAN_CHECK_ONLY;
8565            }
8566        } else {
8567            scanFlags &= ~SCAN_CHECK_ONLY;
8568        }
8569
8570        // Scan the parent
8571        PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags,
8572                scanFlags, currentTime, user);
8573
8574        // Scan the children
8575        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8576        for (int i = 0; i < childCount; i++) {
8577            PackageParser.Package childPackage = pkg.childPackages.get(i);
8578            addForInitLI(childPackage, parseFlags, scanFlags,
8579                    currentTime, user);
8580        }
8581
8582
8583        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8584            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8585        }
8586
8587        return scannedPkg;
8588    }
8589
8590    /**
8591     * Returns if full apk verification can be skipped for the whole package, including the splits.
8592     */
8593    private boolean canSkipFullPackageVerification(PackageParser.Package pkg) {
8594        if (!canSkipFullApkVerification(pkg.baseCodePath)) {
8595            return false;
8596        }
8597        // TODO: Allow base and splits to be verified individually.
8598        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8599            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8600                if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) {
8601                    return false;
8602                }
8603            }
8604        }
8605        return true;
8606    }
8607
8608    /**
8609     * Returns if full apk verification can be skipped, depending on current FSVerity setup and
8610     * whether the apk contains signed root hash.  Note that the signer's certificate still needs to
8611     * match one in a trusted source, and should be done separately.
8612     */
8613    private boolean canSkipFullApkVerification(String apkPath) {
8614        byte[] rootHashObserved = null;
8615        try {
8616            rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath);
8617            if (rootHashObserved == null) {
8618                return false;  // APK does not contain Merkle tree root hash.
8619            }
8620            synchronized (mInstallLock) {
8621                // Returns whether the observed root hash matches what kernel has.
8622                mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved);
8623                return true;
8624            }
8625        } catch (InstallerException | IOException | DigestException |
8626                NoSuchAlgorithmException e) {
8627            Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e);
8628        }
8629        return false;
8630    }
8631
8632    /**
8633     * Adds a new package to the internal data structures during platform initialization.
8634     * <p>After adding, the package is known to the system and available for querying.
8635     * <p>For packages located on the device ROM [eg. packages located in /system, /vendor,
8636     * etc...], additional checks are performed. Basic verification [such as ensuring
8637     * matching signatures, checking version codes, etc...] occurs if the package is
8638     * identical to a previously known package. If the package fails a signature check,
8639     * the version installed on /data will be removed. If the version of the new package
8640     * is less than or equal than the version on /data, it will be ignored.
8641     * <p>Regardless of the package location, the results are applied to the internal
8642     * structures and the package is made available to the rest of the system.
8643     * <p>NOTE: The return value should be removed. It's the passed in package object.
8644     */
8645    private PackageParser.Package addForInitLI(PackageParser.Package pkg,
8646            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8647            @Nullable UserHandle user)
8648                    throws PackageManagerException {
8649        final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0;
8650        final String renamedPkgName;
8651        final PackageSetting disabledPkgSetting;
8652        final boolean isSystemPkgUpdated;
8653        final boolean pkgAlreadyExists;
8654        PackageSetting pkgSetting;
8655
8656        // NOTE: installPackageLI() has the same code to setup the package's
8657        // application info. This probably should be done lower in the call
8658        // stack [such as scanPackageOnly()]. However, we verify the application
8659        // info prior to that [in scanPackageNew()] and thus have to setup
8660        // the application info early.
8661        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8662        pkg.setApplicationInfoCodePath(pkg.codePath);
8663        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8664        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8665        pkg.setApplicationInfoResourcePath(pkg.codePath);
8666        pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
8667        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8668
8669        synchronized (mPackages) {
8670            renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8671            final String realPkgName = getRealPackageName(pkg, renamedPkgName);
8672            if (realPkgName != null) {
8673                ensurePackageRenamed(pkg, renamedPkgName);
8674            }
8675            final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
8676            final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName);
8677            pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting;
8678            pkgAlreadyExists = pkgSetting != null;
8679            final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName;
8680            disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName);
8681            isSystemPkgUpdated = disabledPkgSetting != null;
8682
8683            if (DEBUG_INSTALL && isSystemPkgUpdated) {
8684                Slog.d(TAG, "updatedPkg = " + disabledPkgSetting);
8685            }
8686
8687            final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null)
8688                    ? mSettings.getSharedUserLPw(pkg.mSharedUserId,
8689                            0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true)
8690                    : null;
8691            if (DEBUG_PACKAGE_SCANNING
8692                    && (parseFlags & PackageParser.PARSE_CHATTY) != 0
8693                    && sharedUserSetting != null) {
8694                Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
8695                        + " (uid=" + sharedUserSetting.userId + "):"
8696                        + " packages=" + sharedUserSetting.packages);
8697            }
8698
8699            if (scanSystemPartition) {
8700                // Potentially prune child packages. If the application on the /system
8701                // partition has been updated via OTA, but, is still disabled by a
8702                // version on /data, cycle through all of its children packages and
8703                // remove children that are no longer defined.
8704                if (isSystemPkgUpdated) {
8705                    final int scannedChildCount = (pkg.childPackages != null)
8706                            ? pkg.childPackages.size() : 0;
8707                    final int disabledChildCount = disabledPkgSetting.childPackageNames != null
8708                            ? disabledPkgSetting.childPackageNames.size() : 0;
8709                    for (int i = 0; i < disabledChildCount; i++) {
8710                        String disabledChildPackageName =
8711                                disabledPkgSetting.childPackageNames.get(i);
8712                        boolean disabledPackageAvailable = false;
8713                        for (int j = 0; j < scannedChildCount; j++) {
8714                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8715                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8716                                disabledPackageAvailable = true;
8717                                break;
8718                            }
8719                        }
8720                        if (!disabledPackageAvailable) {
8721                            mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8722                        }
8723                    }
8724                    // we're updating the disabled package, so, scan it as the package setting
8725                    final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, null,
8726                            disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */,
8727                            null /* originalPkgSetting */, null, parseFlags, scanFlags,
8728                            (pkg == mPlatformPackage), user);
8729                    applyPolicy(pkg, parseFlags, scanFlags, mPlatformPackage);
8730                    scanPackageOnlyLI(request, mFactoryTest, -1L);
8731                }
8732            }
8733        }
8734
8735        final boolean newPkgChangedPaths =
8736                pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath);
8737        final boolean newPkgVersionGreater =
8738                pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode;
8739        final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated
8740                && newPkgChangedPaths && newPkgVersionGreater;
8741        if (isSystemPkgBetter) {
8742            // The version of the application on /system is greater than the version on
8743            // /data. Switch back to the application on /system.
8744            // It's safe to assume the application on /system will correctly scan. If not,
8745            // there won't be a working copy of the application.
8746            synchronized (mPackages) {
8747                // just remove the loaded entries from package lists
8748                mPackages.remove(pkgSetting.name);
8749            }
8750
8751            logCriticalInfo(Log.WARN,
8752                    "System package updated;"
8753                    + " name: " + pkgSetting.name
8754                    + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8755                    + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8756
8757            final InstallArgs args = createInstallArgsForExisting(
8758                    packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8759                    pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8760            args.cleanUpResourcesLI();
8761            synchronized (mPackages) {
8762                mSettings.enableSystemPackageLPw(pkgSetting.name);
8763            }
8764        }
8765
8766        if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) {
8767            // The version of the application on the /system partition is less than or
8768            // equal to the version on the /data partition. Throw an exception and use
8769            // the application already installed on the /data partition.
8770            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8771                    + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode
8772                    + " better than this " + pkg.getLongVersionCode());
8773        }
8774
8775        // Verify certificates against what was last scanned. If it is an updated priv app, we will
8776        // force re-collecting certificate.
8777        final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced(
8778                disabledPkgSetting);
8779        // Full APK verification can be skipped during certificate collection, only if the file is
8780        // in verified partition, or can be verified on access (when apk verity is enabled). In both
8781        // cases, only data in Signing Block is verified instead of the whole file.
8782        final boolean skipVerify = ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) ||
8783                (forceCollect && canSkipFullPackageVerification(pkg));
8784        collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify);
8785
8786        // Reset profile if the application version is changed
8787        maybeClearProfilesForUpgradesLI(pkgSetting, pkg);
8788
8789        /*
8790         * A new system app appeared, but we already had a non-system one of the
8791         * same name installed earlier.
8792         */
8793        boolean shouldHideSystemApp = false;
8794        // A new application appeared on /system, but, we already have a copy of
8795        // the application installed on /data.
8796        if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists
8797                && !pkgSetting.isSystem()) {
8798
8799            if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails,
8800                    PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)
8801                            && !pkgSetting.signatures.mSigningDetails.checkCapability(
8802                                    pkg.mSigningDetails,
8803                                    PackageParser.SigningDetails.CertCapabilities.ROLLBACK)) {
8804                logCriticalInfo(Log.WARN,
8805                        "System package signature mismatch;"
8806                        + " name: " + pkgSetting.name);
8807                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8808                        "scanPackageInternalLI")) {
8809                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8810                }
8811                pkgSetting = null;
8812            } else if (newPkgVersionGreater) {
8813                // The application on /system is newer than the application on /data.
8814                // Simply remove the application on /data [keeping application data]
8815                // and replace it with the version on /system.
8816                logCriticalInfo(Log.WARN,
8817                        "System package enabled;"
8818                        + " name: " + pkgSetting.name
8819                        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8820                        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8821                InstallArgs args = createInstallArgsForExisting(
8822                        packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8823                        pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8824                synchronized (mInstallLock) {
8825                    args.cleanUpResourcesLI();
8826                }
8827            } else {
8828                // The application on /system is older than the application on /data. Hide
8829                // the application on /system and the version on /data will be scanned later
8830                // and re-added like an update.
8831                shouldHideSystemApp = true;
8832                logCriticalInfo(Log.INFO,
8833                        "System package disabled;"
8834                        + " name: " + pkgSetting.name
8835                        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8836                        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8837            }
8838        }
8839
8840        final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8841                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8842
8843        if (shouldHideSystemApp) {
8844            synchronized (mPackages) {
8845                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8846            }
8847        }
8848        return scannedPkg;
8849    }
8850
8851    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8852        // Derive the new package synthetic package name
8853        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8854                + pkg.staticSharedLibVersion);
8855    }
8856
8857    private static String fixProcessName(String defProcessName,
8858            String processName) {
8859        if (processName == null) {
8860            return defProcessName;
8861        }
8862        return processName;
8863    }
8864
8865    /**
8866     * Enforces that only the system UID or root's UID can call a method exposed
8867     * via Binder.
8868     *
8869     * @param message used as message if SecurityException is thrown
8870     * @throws SecurityException if the caller is not system or root
8871     */
8872    private static final void enforceSystemOrRoot(String message) {
8873        final int uid = Binder.getCallingUid();
8874        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8875            throw new SecurityException(message);
8876        }
8877    }
8878
8879    @Override
8880    public void performFstrimIfNeeded() {
8881        enforceSystemOrRoot("Only the system can request fstrim");
8882
8883        // Before everything else, see whether we need to fstrim.
8884        try {
8885            IStorageManager sm = PackageHelper.getStorageManager();
8886            if (sm != null) {
8887                boolean doTrim = false;
8888                final long interval = android.provider.Settings.Global.getLong(
8889                        mContext.getContentResolver(),
8890                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8891                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8892                if (interval > 0) {
8893                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8894                    if (timeSinceLast > interval) {
8895                        doTrim = true;
8896                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8897                                + "; running immediately");
8898                    }
8899                }
8900                if (doTrim) {
8901                    final boolean dexOptDialogShown;
8902                    synchronized (mPackages) {
8903                        dexOptDialogShown = mDexOptDialogShown;
8904                    }
8905                    if (!isFirstBoot() && dexOptDialogShown) {
8906                        try {
8907                            ActivityManager.getService().showBootMessage(
8908                                    mContext.getResources().getString(
8909                                            R.string.android_upgrading_fstrim), true);
8910                        } catch (RemoteException e) {
8911                        }
8912                    }
8913                    sm.runMaintenance();
8914                }
8915            } else {
8916                Slog.e(TAG, "storageManager service unavailable!");
8917            }
8918        } catch (RemoteException e) {
8919            // Can't happen; StorageManagerService is local
8920        }
8921    }
8922
8923    @Override
8924    public void updatePackagesIfNeeded() {
8925        enforceSystemOrRoot("Only the system can request package update");
8926
8927        // We need to re-extract after an OTA.
8928        boolean causeUpgrade = isUpgrade();
8929
8930        // First boot or factory reset.
8931        // Note: we also handle devices that are upgrading to N right now as if it is their
8932        //       first boot, as they do not have profile data.
8933        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8934
8935        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8936        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8937
8938        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8939            return;
8940        }
8941
8942        List<PackageParser.Package> pkgs;
8943        synchronized (mPackages) {
8944            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8945        }
8946
8947        final long startTime = System.nanoTime();
8948        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8949                    causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
8950                    false /* bootComplete */);
8951
8952        final int elapsedTimeSeconds =
8953                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8954
8955        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8956        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8957        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8958        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8959        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8960    }
8961
8962    /*
8963     * Return the prebuilt profile path given a package base code path.
8964     */
8965    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8966        return pkg.baseCodePath + ".prof";
8967    }
8968
8969    /**
8970     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8971     * containing statistics about the invocation. The array consists of three elements,
8972     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8973     * and {@code numberOfPackagesFailed}.
8974     */
8975    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8976            final int compilationReason, boolean bootComplete) {
8977
8978        int numberOfPackagesVisited = 0;
8979        int numberOfPackagesOptimized = 0;
8980        int numberOfPackagesSkipped = 0;
8981        int numberOfPackagesFailed = 0;
8982        final int numberOfPackagesToDexopt = pkgs.size();
8983
8984        for (PackageParser.Package pkg : pkgs) {
8985            numberOfPackagesVisited++;
8986
8987            boolean useProfileForDexopt = false;
8988
8989            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8990                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8991                // that are already compiled.
8992                File profileFile = new File(getPrebuildProfilePath(pkg));
8993                // Copy profile if it exists.
8994                if (profileFile.exists()) {
8995                    try {
8996                        // We could also do this lazily before calling dexopt in
8997                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8998                        // is that we don't have a good way to say "do this only once".
8999                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9000                                pkg.applicationInfo.uid, pkg.packageName,
9001                                ArtManager.getProfileName(null))) {
9002                            Log.e(TAG, "Installer failed to copy system profile!");
9003                        } else {
9004                            // Disabled as this causes speed-profile compilation during first boot
9005                            // even if things are already compiled.
9006                            // useProfileForDexopt = true;
9007                        }
9008                    } catch (Exception e) {
9009                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9010                                e);
9011                    }
9012                } else {
9013                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9014                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
9015                    // minimize the number off apps being speed-profile compiled during first boot.
9016                    // The other paths will not change the filter.
9017                    if (disabledPs != null && disabledPs.pkg.isStub) {
9018                        // The package is the stub one, remove the stub suffix to get the normal
9019                        // package and APK names.
9020                        String systemProfilePath =
9021                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
9022                        profileFile = new File(systemProfilePath);
9023                        // If we have a profile for a compressed APK, copy it to the reference
9024                        // location.
9025                        // Note that copying the profile here will cause it to override the
9026                        // reference profile every OTA even though the existing reference profile
9027                        // may have more data. We can't copy during decompression since the
9028                        // directories are not set up at that point.
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
9033                                // issue is that we don't have a good way to say "do this only
9034                                // once".
9035                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9036                                        pkg.applicationInfo.uid, pkg.packageName,
9037                                        ArtManager.getProfileName(null))) {
9038                                    Log.e(TAG, "Failed to copy system profile for stub package!");
9039                                } else {
9040                                    useProfileForDexopt = true;
9041                                }
9042                            } catch (Exception e) {
9043                                Log.e(TAG, "Failed to copy profile " +
9044                                        profileFile.getAbsolutePath() + " ", e);
9045                            }
9046                        }
9047                    }
9048                }
9049            }
9050
9051            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9052                if (DEBUG_DEXOPT) {
9053                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9054                }
9055                numberOfPackagesSkipped++;
9056                continue;
9057            }
9058
9059            if (DEBUG_DEXOPT) {
9060                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9061                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9062            }
9063
9064            if (showDialog) {
9065                try {
9066                    ActivityManager.getService().showBootMessage(
9067                            mContext.getResources().getString(R.string.android_upgrading_apk,
9068                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9069                } catch (RemoteException e) {
9070                }
9071                synchronized (mPackages) {
9072                    mDexOptDialogShown = true;
9073                }
9074            }
9075
9076            int pkgCompilationReason = compilationReason;
9077            if (useProfileForDexopt) {
9078                // Use background dexopt mode to try and use the profile. Note that this does not
9079                // guarantee usage of the profile.
9080                pkgCompilationReason = PackageManagerService.REASON_BACKGROUND_DEXOPT;
9081            }
9082
9083            // checkProfiles is false to avoid merging profiles during boot which
9084            // might interfere with background compilation (b/28612421).
9085            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9086            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9087            // trade-off worth doing to save boot time work.
9088            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9089            if (compilationReason == REASON_FIRST_BOOT) {
9090                // TODO: This doesn't cover the upgrade case, we should check for this too.
9091                dexoptFlags |= DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE;
9092            }
9093            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9094                    pkg.packageName,
9095                    pkgCompilationReason,
9096                    dexoptFlags));
9097
9098            switch (primaryDexOptStaus) {
9099                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9100                    numberOfPackagesOptimized++;
9101                    break;
9102                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9103                    numberOfPackagesSkipped++;
9104                    break;
9105                case PackageDexOptimizer.DEX_OPT_FAILED:
9106                    numberOfPackagesFailed++;
9107                    break;
9108                default:
9109                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9110                    break;
9111            }
9112        }
9113
9114        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9115                numberOfPackagesFailed };
9116    }
9117
9118    @Override
9119    public void notifyPackageUse(String packageName, int reason) {
9120        synchronized (mPackages) {
9121            final int callingUid = Binder.getCallingUid();
9122            final int callingUserId = UserHandle.getUserId(callingUid);
9123            if (getInstantAppPackageName(callingUid) != null) {
9124                if (!isCallerSameApp(packageName, callingUid)) {
9125                    return;
9126                }
9127            } else {
9128                if (isInstantApp(packageName, callingUserId)) {
9129                    return;
9130                }
9131            }
9132            notifyPackageUseLocked(packageName, reason);
9133        }
9134    }
9135
9136    @GuardedBy("mPackages")
9137    private void notifyPackageUseLocked(String packageName, int reason) {
9138        final PackageParser.Package p = mPackages.get(packageName);
9139        if (p == null) {
9140            return;
9141        }
9142        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9143    }
9144
9145    @Override
9146    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9147            List<String> classPaths, String loaderIsa) {
9148        int userId = UserHandle.getCallingUserId();
9149        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9150        if (ai == null) {
9151            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9152                + loadingPackageName + ", user=" + userId);
9153            return;
9154        }
9155        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9156    }
9157
9158    @Override
9159    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9160            IDexModuleRegisterCallback callback) {
9161        int userId = UserHandle.getCallingUserId();
9162        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9163        DexManager.RegisterDexModuleResult result;
9164        if (ai == null) {
9165            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9166                     " calling user. package=" + packageName + ", user=" + userId);
9167            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9168        } else {
9169            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9170        }
9171
9172        if (callback != null) {
9173            mHandler.post(() -> {
9174                try {
9175                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9176                } catch (RemoteException e) {
9177                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9178                }
9179            });
9180        }
9181    }
9182
9183    /**
9184     * Ask the package manager to perform a dex-opt with the given compiler filter.
9185     *
9186     * Note: exposed only for the shell command to allow moving packages explicitly to a
9187     *       definite state.
9188     */
9189    @Override
9190    public boolean performDexOptMode(String packageName,
9191            boolean checkProfiles, String targetCompilerFilter, boolean force,
9192            boolean bootComplete, String splitName) {
9193        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9194                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9195                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9196        return performDexOpt(new DexoptOptions(packageName, REASON_UNKNOWN,
9197                targetCompilerFilter, splitName, flags));
9198    }
9199
9200    /**
9201     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9202     * secondary dex files belonging to the given package.
9203     *
9204     * Note: exposed only for the shell command to allow moving packages explicitly to a
9205     *       definite state.
9206     */
9207    @Override
9208    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9209            boolean force) {
9210        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9211                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9212                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9213                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9214        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9215    }
9216
9217    /*package*/ boolean performDexOpt(DexoptOptions options) {
9218        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9219            return false;
9220        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9221            return false;
9222        }
9223
9224        if (options.isDexoptOnlySecondaryDex()) {
9225            return mDexManager.dexoptSecondaryDex(options);
9226        } else {
9227            int dexoptStatus = performDexOptWithStatus(options);
9228            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9229        }
9230    }
9231
9232    /**
9233     * Perform dexopt on the given package and return one of following result:
9234     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9235     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9236     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9237     */
9238    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9239        return performDexOptTraced(options);
9240    }
9241
9242    private int performDexOptTraced(DexoptOptions options) {
9243        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9244        try {
9245            return performDexOptInternal(options);
9246        } finally {
9247            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9248        }
9249    }
9250
9251    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9252    // if the package can now be considered up to date for the given filter.
9253    private int performDexOptInternal(DexoptOptions options) {
9254        PackageParser.Package p;
9255        synchronized (mPackages) {
9256            p = mPackages.get(options.getPackageName());
9257            if (p == null) {
9258                // Package could not be found. Report failure.
9259                return PackageDexOptimizer.DEX_OPT_FAILED;
9260            }
9261            mPackageUsage.maybeWriteAsync(mPackages);
9262            mCompilerStats.maybeWriteAsync();
9263        }
9264        long callingId = Binder.clearCallingIdentity();
9265        try {
9266            synchronized (mInstallLock) {
9267                return performDexOptInternalWithDependenciesLI(p, options);
9268            }
9269        } finally {
9270            Binder.restoreCallingIdentity(callingId);
9271        }
9272    }
9273
9274    public ArraySet<String> getOptimizablePackages() {
9275        ArraySet<String> pkgs = new ArraySet<String>();
9276        synchronized (mPackages) {
9277            for (PackageParser.Package p : mPackages.values()) {
9278                if (PackageDexOptimizer.canOptimizePackage(p)) {
9279                    pkgs.add(p.packageName);
9280                }
9281            }
9282        }
9283        return pkgs;
9284    }
9285
9286    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9287            DexoptOptions options) {
9288        // Select the dex optimizer based on the force parameter.
9289        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9290        //       allocate an object here.
9291        PackageDexOptimizer pdo = options.isForce()
9292                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9293                : mPackageDexOptimizer;
9294
9295        // Dexopt all dependencies first. Note: we ignore the return value and march on
9296        // on errors.
9297        // Note that we are going to call performDexOpt on those libraries as many times as
9298        // they are referenced in packages. When we do a batch of performDexOpt (for example
9299        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9300        // and the first package that uses the library will dexopt it. The
9301        // others will see that the compiled code for the library is up to date.
9302        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9303        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9304        if (!deps.isEmpty()) {
9305            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9306                    options.getCompilationReason(), options.getCompilerFilter(),
9307                    options.getSplitName(),
9308                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9309            for (PackageParser.Package depPackage : deps) {
9310                // TODO: Analyze and investigate if we (should) profile libraries.
9311                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9312                        getOrCreateCompilerPackageStats(depPackage),
9313                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9314            }
9315        }
9316        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9317                getOrCreateCompilerPackageStats(p),
9318                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9319    }
9320
9321    /**
9322     * Reconcile the information we have about the secondary dex files belonging to
9323     * {@code packagName} and the actual dex files. For all dex files that were
9324     * deleted, update the internal records and delete the generated oat files.
9325     */
9326    @Override
9327    public void reconcileSecondaryDexFiles(String packageName) {
9328        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9329            return;
9330        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9331            return;
9332        }
9333        mDexManager.reconcileSecondaryDexFiles(packageName);
9334    }
9335
9336    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9337    // a reference there.
9338    /*package*/ DexManager getDexManager() {
9339        return mDexManager;
9340    }
9341
9342    /**
9343     * Execute the background dexopt job immediately.
9344     */
9345    @Override
9346    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9347        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9348            return false;
9349        }
9350        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9351    }
9352
9353    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9354        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9355                || p.usesStaticLibraries != null) {
9356            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9357            Set<String> collectedNames = new HashSet<>();
9358            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9359
9360            retValue.remove(p);
9361
9362            return retValue;
9363        } else {
9364            return Collections.emptyList();
9365        }
9366    }
9367
9368    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9369            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9370        if (!collectedNames.contains(p.packageName)) {
9371            collectedNames.add(p.packageName);
9372            collected.add(p);
9373
9374            if (p.usesLibraries != null) {
9375                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9376                        null, collected, collectedNames);
9377            }
9378            if (p.usesOptionalLibraries != null) {
9379                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9380                        null, collected, collectedNames);
9381            }
9382            if (p.usesStaticLibraries != null) {
9383                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9384                        p.usesStaticLibrariesVersions, collected, collectedNames);
9385            }
9386        }
9387    }
9388
9389    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9390            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9391        final int libNameCount = libs.size();
9392        for (int i = 0; i < libNameCount; i++) {
9393            String libName = libs.get(i);
9394            long version = (versions != null && versions.length == libNameCount)
9395                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9396            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9397            if (libPkg != null) {
9398                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9399            }
9400        }
9401    }
9402
9403    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9404        synchronized (mPackages) {
9405            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9406            if (libEntry != null) {
9407                return mPackages.get(libEntry.apk);
9408            }
9409            return null;
9410        }
9411    }
9412
9413    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9414        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9415        if (versionedLib == null) {
9416            return null;
9417        }
9418        return versionedLib.get(version);
9419    }
9420
9421    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9422        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9423                pkg.staticSharedLibName);
9424        if (versionedLib == null) {
9425            return null;
9426        }
9427        long previousLibVersion = -1;
9428        final int versionCount = versionedLib.size();
9429        for (int i = 0; i < versionCount; i++) {
9430            final long libVersion = versionedLib.keyAt(i);
9431            if (libVersion < pkg.staticSharedLibVersion) {
9432                previousLibVersion = Math.max(previousLibVersion, libVersion);
9433            }
9434        }
9435        if (previousLibVersion >= 0) {
9436            return versionedLib.get(previousLibVersion);
9437        }
9438        return null;
9439    }
9440
9441    public void shutdown() {
9442        mPackageUsage.writeNow(mPackages);
9443        mCompilerStats.writeNow();
9444        mDexManager.writePackageDexUsageNow();
9445
9446        // This is the last chance to write out pending restriction settings
9447        synchronized (mPackages) {
9448            if (mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
9449                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
9450                for (int userId : mDirtyUsers) {
9451                    mSettings.writePackageRestrictionsLPr(userId);
9452                }
9453                mDirtyUsers.clear();
9454            }
9455        }
9456    }
9457
9458    @Override
9459    public void dumpProfiles(String packageName) {
9460        PackageParser.Package pkg;
9461        synchronized (mPackages) {
9462            pkg = mPackages.get(packageName);
9463            if (pkg == null) {
9464                throw new IllegalArgumentException("Unknown package: " + packageName);
9465            }
9466        }
9467        /* Only the shell, root, or the app user should be able to dump profiles. */
9468        int callingUid = Binder.getCallingUid();
9469        if (callingUid != Process.SHELL_UID &&
9470            callingUid != Process.ROOT_UID &&
9471            callingUid != pkg.applicationInfo.uid) {
9472            throw new SecurityException("dumpProfiles");
9473        }
9474
9475        synchronized (mInstallLock) {
9476            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9477            mArtManagerService.dumpProfiles(pkg);
9478            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9479        }
9480    }
9481
9482    @Override
9483    public void forceDexOpt(String packageName) {
9484        enforceSystemOrRoot("forceDexOpt");
9485
9486        PackageParser.Package pkg;
9487        synchronized (mPackages) {
9488            pkg = mPackages.get(packageName);
9489            if (pkg == null) {
9490                throw new IllegalArgumentException("Unknown package: " + packageName);
9491            }
9492        }
9493
9494        synchronized (mInstallLock) {
9495            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9496
9497            // Whoever is calling forceDexOpt wants a compiled package.
9498            // Don't use profiles since that may cause compilation to be skipped.
9499            final int res = performDexOptInternalWithDependenciesLI(
9500                    pkg,
9501                    new DexoptOptions(packageName,
9502                            getDefaultCompilerFilter(),
9503                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9504
9505            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9506            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9507                throw new IllegalStateException("Failed to dexopt: " + res);
9508            }
9509        }
9510    }
9511
9512    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9513        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9514            Slog.w(TAG, "Unable to update from " + oldPkg.name
9515                    + " to " + newPkg.packageName
9516                    + ": old package not in system partition");
9517            return false;
9518        } else if (mPackages.get(oldPkg.name) != null) {
9519            Slog.w(TAG, "Unable to update from " + oldPkg.name
9520                    + " to " + newPkg.packageName
9521                    + ": old package still exists");
9522            return false;
9523        }
9524        return true;
9525    }
9526
9527    void removeCodePathLI(File codePath) {
9528        if (codePath.isDirectory()) {
9529            try {
9530                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9531            } catch (InstallerException e) {
9532                Slog.w(TAG, "Failed to remove code path", e);
9533            }
9534        } else {
9535            codePath.delete();
9536        }
9537    }
9538
9539    private int[] resolveUserIds(int userId) {
9540        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9541    }
9542
9543    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9544        if (pkg == null) {
9545            Slog.wtf(TAG, "Package was null!", new Throwable());
9546            return;
9547        }
9548        clearAppDataLeafLIF(pkg, userId, flags);
9549        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9550        for (int i = 0; i < childCount; i++) {
9551            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9552        }
9553
9554        clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
9555    }
9556
9557    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9558        final PackageSetting ps;
9559        synchronized (mPackages) {
9560            ps = mSettings.mPackages.get(pkg.packageName);
9561        }
9562        for (int realUserId : resolveUserIds(userId)) {
9563            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9564            try {
9565                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9566                        ceDataInode);
9567            } catch (InstallerException e) {
9568                Slog.w(TAG, String.valueOf(e));
9569            }
9570        }
9571    }
9572
9573    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9574        if (pkg == null) {
9575            Slog.wtf(TAG, "Package was null!", new Throwable());
9576            return;
9577        }
9578        destroyAppDataLeafLIF(pkg, userId, flags);
9579        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9580        for (int i = 0; i < childCount; i++) {
9581            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9582        }
9583    }
9584
9585    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9586        final PackageSetting ps;
9587        synchronized (mPackages) {
9588            ps = mSettings.mPackages.get(pkg.packageName);
9589        }
9590        for (int realUserId : resolveUserIds(userId)) {
9591            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9592            try {
9593                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9594                        ceDataInode);
9595            } catch (InstallerException e) {
9596                Slog.w(TAG, String.valueOf(e));
9597            }
9598            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9599        }
9600    }
9601
9602    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9603        if (pkg == null) {
9604            Slog.wtf(TAG, "Package was null!", new Throwable());
9605            return;
9606        }
9607        destroyAppProfilesLeafLIF(pkg);
9608        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9609        for (int i = 0; i < childCount; i++) {
9610            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9611        }
9612    }
9613
9614    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9615        try {
9616            mInstaller.destroyAppProfiles(pkg.packageName);
9617        } catch (InstallerException e) {
9618            Slog.w(TAG, String.valueOf(e));
9619        }
9620    }
9621
9622    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9623        if (pkg == null) {
9624            Slog.wtf(TAG, "Package was null!", new Throwable());
9625            return;
9626        }
9627        mArtManagerService.clearAppProfiles(pkg);
9628        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9629        for (int i = 0; i < childCount; i++) {
9630            mArtManagerService.clearAppProfiles(pkg.childPackages.get(i));
9631        }
9632    }
9633
9634    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9635            long lastUpdateTime) {
9636        // Set parent install/update time
9637        PackageSetting ps = (PackageSetting) pkg.mExtras;
9638        if (ps != null) {
9639            ps.firstInstallTime = firstInstallTime;
9640            ps.lastUpdateTime = lastUpdateTime;
9641        }
9642        // Set children install/update time
9643        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9644        for (int i = 0; i < childCount; i++) {
9645            PackageParser.Package childPkg = pkg.childPackages.get(i);
9646            ps = (PackageSetting) childPkg.mExtras;
9647            if (ps != null) {
9648                ps.firstInstallTime = firstInstallTime;
9649                ps.lastUpdateTime = lastUpdateTime;
9650            }
9651        }
9652    }
9653
9654    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9655            SharedLibraryEntry file,
9656            PackageParser.Package changingLib) {
9657        if (file.path != null) {
9658            usesLibraryFiles.add(file.path);
9659            return;
9660        }
9661        PackageParser.Package p = mPackages.get(file.apk);
9662        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9663            // If we are doing this while in the middle of updating a library apk,
9664            // then we need to make sure to use that new apk for determining the
9665            // dependencies here.  (We haven't yet finished committing the new apk
9666            // to the package manager state.)
9667            if (p == null || p.packageName.equals(changingLib.packageName)) {
9668                p = changingLib;
9669            }
9670        }
9671        if (p != null) {
9672            usesLibraryFiles.addAll(p.getAllCodePaths());
9673            if (p.usesLibraryFiles != null) {
9674                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9675            }
9676        }
9677    }
9678
9679    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9680            PackageParser.Package changingLib) throws PackageManagerException {
9681        if (pkg == null) {
9682            return;
9683        }
9684        // The collection used here must maintain the order of addition (so
9685        // that libraries are searched in the correct order) and must have no
9686        // duplicates.
9687        Set<String> usesLibraryFiles = null;
9688        if (pkg.usesLibraries != null) {
9689            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9690                    null, null, pkg.packageName, changingLib, true,
9691                    pkg.applicationInfo.targetSdkVersion, null);
9692        }
9693        if (pkg.usesStaticLibraries != null) {
9694            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9695                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9696                    pkg.packageName, changingLib, true,
9697                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9698        }
9699        if (pkg.usesOptionalLibraries != null) {
9700            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9701                    null, null, pkg.packageName, changingLib, false,
9702                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9703        }
9704        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9705            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9706        } else {
9707            pkg.usesLibraryFiles = null;
9708        }
9709    }
9710
9711    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9712            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9713            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9714            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9715            throws PackageManagerException {
9716        final int libCount = requestedLibraries.size();
9717        for (int i = 0; i < libCount; i++) {
9718            final String libName = requestedLibraries.get(i);
9719            final long libVersion = requiredVersions != null ? requiredVersions[i]
9720                    : SharedLibraryInfo.VERSION_UNDEFINED;
9721            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9722            if (libEntry == null) {
9723                if (required) {
9724                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9725                            "Package " + packageName + " requires unavailable shared library "
9726                                    + libName + "; failing!");
9727                } else if (DEBUG_SHARED_LIBRARIES) {
9728                    Slog.i(TAG, "Package " + packageName
9729                            + " desires unavailable shared library "
9730                            + libName + "; ignoring!");
9731                }
9732            } else {
9733                if (requiredVersions != null && requiredCertDigests != null) {
9734                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9735                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9736                            "Package " + packageName + " requires unavailable static shared"
9737                                    + " library " + libName + " version "
9738                                    + libEntry.info.getLongVersion() + "; failing!");
9739                    }
9740
9741                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9742                    if (libPkg == null) {
9743                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9744                                "Package " + packageName + " requires unavailable static shared"
9745                                        + " library; failing!");
9746                    }
9747
9748                    final String[] expectedCertDigests = requiredCertDigests[i];
9749
9750
9751                    if (expectedCertDigests.length > 1) {
9752
9753                        // For apps targeting O MR1 we require explicit enumeration of all certs.
9754                        final String[] libCertDigests = (targetSdk >= Build.VERSION_CODES.O_MR1)
9755                                ? PackageUtils.computeSignaturesSha256Digests(
9756                                libPkg.mSigningDetails.signatures)
9757                                : PackageUtils.computeSignaturesSha256Digests(
9758                                        new Signature[]{libPkg.mSigningDetails.signatures[0]});
9759
9760                        // Take a shortcut if sizes don't match. Note that if an app doesn't
9761                        // target O we don't parse the "additional-certificate" tags similarly
9762                        // how we only consider all certs only for apps targeting O (see above).
9763                        // Therefore, the size check is safe to make.
9764                        if (expectedCertDigests.length != libCertDigests.length) {
9765                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9766                                    "Package " + packageName + " requires differently signed" +
9767                                            " static shared library; failing!");
9768                        }
9769
9770                        // Use a predictable order as signature order may vary
9771                        Arrays.sort(libCertDigests);
9772                        Arrays.sort(expectedCertDigests);
9773
9774                        final int certCount = libCertDigests.length;
9775                        for (int j = 0; j < certCount; j++) {
9776                            if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9777                                throw new PackageManagerException(
9778                                        INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9779                                        "Package " + packageName + " requires differently signed" +
9780                                                " static shared library; failing!");
9781                            }
9782                        }
9783                    } else {
9784
9785                        // lib signing cert could have rotated beyond the one expected, check to see
9786                        // if the new one has been blessed by the old
9787                        if (!libPkg.mSigningDetails.hasSha256Certificate(
9788                                ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) {
9789                            throw new PackageManagerException(
9790                                    INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9791                                    "Package " + packageName + " requires differently signed" +
9792                                            " static shared library; failing!");
9793                        }
9794                    }
9795                }
9796
9797                if (outUsedLibraries == null) {
9798                    // Use LinkedHashSet to preserve the order of files added to
9799                    // usesLibraryFiles while eliminating duplicates.
9800                    outUsedLibraries = new LinkedHashSet<>();
9801                }
9802                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9803            }
9804        }
9805        return outUsedLibraries;
9806    }
9807
9808    private static boolean hasString(List<String> list, List<String> which) {
9809        if (list == null) {
9810            return false;
9811        }
9812        for (int i=list.size()-1; i>=0; i--) {
9813            for (int j=which.size()-1; j>=0; j--) {
9814                if (which.get(j).equals(list.get(i))) {
9815                    return true;
9816                }
9817            }
9818        }
9819        return false;
9820    }
9821
9822    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9823            PackageParser.Package changingPkg) {
9824        ArrayList<PackageParser.Package> res = null;
9825        for (PackageParser.Package pkg : mPackages.values()) {
9826            if (changingPkg != null
9827                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9828                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9829                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9830                            changingPkg.staticSharedLibName)) {
9831                return null;
9832            }
9833            if (res == null) {
9834                res = new ArrayList<>();
9835            }
9836            res.add(pkg);
9837            try {
9838                updateSharedLibrariesLPr(pkg, changingPkg);
9839            } catch (PackageManagerException e) {
9840                // If a system app update or an app and a required lib missing we
9841                // delete the package and for updated system apps keep the data as
9842                // it is better for the user to reinstall than to be in an limbo
9843                // state. Also libs disappearing under an app should never happen
9844                // - just in case.
9845                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9846                    final int flags = pkg.isUpdatedSystemApp()
9847                            ? PackageManager.DELETE_KEEP_DATA : 0;
9848                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9849                            flags , null, true, null);
9850                }
9851                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9852            }
9853        }
9854        return res;
9855    }
9856
9857    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9858            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9859            @Nullable UserHandle user) throws PackageManagerException {
9860        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9861        // If the package has children and this is the first dive in the function
9862        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9863        // whether all packages (parent and children) would be successfully scanned
9864        // before the actual scan since scanning mutates internal state and we want
9865        // to atomically install the package and its children.
9866        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9867            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9868                scanFlags |= SCAN_CHECK_ONLY;
9869            }
9870        } else {
9871            scanFlags &= ~SCAN_CHECK_ONLY;
9872        }
9873
9874        final PackageParser.Package scannedPkg;
9875        try {
9876            // Scan the parent
9877            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9878            // Scan the children
9879            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9880            for (int i = 0; i < childCount; i++) {
9881                PackageParser.Package childPkg = pkg.childPackages.get(i);
9882                scanPackageNewLI(childPkg, parseFlags,
9883                        scanFlags, currentTime, user);
9884            }
9885        } finally {
9886            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9887        }
9888
9889        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9890            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9891        }
9892
9893        return scannedPkg;
9894    }
9895
9896    /** The result of a package scan. */
9897    private static class ScanResult {
9898        /** Whether or not the package scan was successful */
9899        public final boolean success;
9900        /**
9901         * The final package settings. This may be the same object passed in
9902         * the {@link ScanRequest}, but, with modified values.
9903         */
9904        @Nullable public final PackageSetting pkgSetting;
9905        /** ABI code paths that have changed in the package scan */
9906        @Nullable public final List<String> changedAbiCodePath;
9907        public ScanResult(
9908                boolean success,
9909                @Nullable PackageSetting pkgSetting,
9910                @Nullable List<String> changedAbiCodePath) {
9911            this.success = success;
9912            this.pkgSetting = pkgSetting;
9913            this.changedAbiCodePath = changedAbiCodePath;
9914        }
9915    }
9916
9917    /** A package to be scanned */
9918    private static class ScanRequest {
9919        /** The parsed package */
9920        @NonNull public final PackageParser.Package pkg;
9921        /** The package this package replaces */
9922        @Nullable public final PackageParser.Package oldPkg;
9923        /** Shared user settings, if the package has a shared user */
9924        @Nullable public final SharedUserSetting sharedUserSetting;
9925        /**
9926         * Package settings of the currently installed version.
9927         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9928         * during scan.
9929         */
9930        @Nullable public final PackageSetting pkgSetting;
9931        /** A copy of the settings for the currently installed version */
9932        @Nullable public final PackageSetting oldPkgSetting;
9933        /** Package settings for the disabled version on the /system partition */
9934        @Nullable public final PackageSetting disabledPkgSetting;
9935        /** Package settings for the installed version under its original package name */
9936        @Nullable public final PackageSetting originalPkgSetting;
9937        /** The real package name of a renamed application */
9938        @Nullable public final String realPkgName;
9939        public final @ParseFlags int parseFlags;
9940        public final @ScanFlags int scanFlags;
9941        /** The user for which the package is being scanned */
9942        @Nullable public final UserHandle user;
9943        /** Whether or not the platform package is being scanned */
9944        public final boolean isPlatformPackage;
9945        public ScanRequest(
9946                @NonNull PackageParser.Package pkg,
9947                @Nullable SharedUserSetting sharedUserSetting,
9948                @Nullable PackageParser.Package oldPkg,
9949                @Nullable PackageSetting pkgSetting,
9950                @Nullable PackageSetting disabledPkgSetting,
9951                @Nullable PackageSetting originalPkgSetting,
9952                @Nullable String realPkgName,
9953                @ParseFlags int parseFlags,
9954                @ScanFlags int scanFlags,
9955                boolean isPlatformPackage,
9956                @Nullable UserHandle user) {
9957            this.pkg = pkg;
9958            this.oldPkg = oldPkg;
9959            this.pkgSetting = pkgSetting;
9960            this.sharedUserSetting = sharedUserSetting;
9961            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9962            this.disabledPkgSetting = disabledPkgSetting;
9963            this.originalPkgSetting = originalPkgSetting;
9964            this.realPkgName = realPkgName;
9965            this.parseFlags = parseFlags;
9966            this.scanFlags = scanFlags;
9967            this.isPlatformPackage = isPlatformPackage;
9968            this.user = user;
9969        }
9970    }
9971
9972    /**
9973     * Returns the actual scan flags depending upon the state of the other settings.
9974     * <p>Updated system applications will not have the following flags set
9975     * by default and need to be adjusted after the fact:
9976     * <ul>
9977     * <li>{@link #SCAN_AS_SYSTEM}</li>
9978     * <li>{@link #SCAN_AS_PRIVILEGED}</li>
9979     * <li>{@link #SCAN_AS_OEM}</li>
9980     * <li>{@link #SCAN_AS_VENDOR}</li>
9981     * <li>{@link #SCAN_AS_PRODUCT}</li>
9982     * <li>{@link #SCAN_AS_INSTANT_APP}</li>
9983     * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li>
9984     * </ul>
9985     */
9986    private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags,
9987            PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user,
9988            PackageParser.Package pkg) {
9989        if (disabledPkgSetting != null) {
9990            // updated system application, must at least have SCAN_AS_SYSTEM
9991            scanFlags |= SCAN_AS_SYSTEM;
9992            if ((disabledPkgSetting.pkgPrivateFlags
9993                    & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9994                scanFlags |= SCAN_AS_PRIVILEGED;
9995            }
9996            if ((disabledPkgSetting.pkgPrivateFlags
9997                    & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
9998                scanFlags |= SCAN_AS_OEM;
9999            }
10000            if ((disabledPkgSetting.pkgPrivateFlags
10001                    & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
10002                scanFlags |= SCAN_AS_VENDOR;
10003            }
10004            if ((disabledPkgSetting.pkgPrivateFlags
10005                    & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) {
10006                scanFlags |= SCAN_AS_PRODUCT;
10007            }
10008        }
10009        if (pkgSetting != null) {
10010            final int userId = ((user == null) ? 0 : user.getIdentifier());
10011            if (pkgSetting.getInstantApp(userId)) {
10012                scanFlags |= SCAN_AS_INSTANT_APP;
10013            }
10014            if (pkgSetting.getVirtulalPreload(userId)) {
10015                scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
10016            }
10017        }
10018
10019        // Scan as privileged apps that share a user with a priv-app.
10020        final boolean skipVendorPrivilegeScan = ((scanFlags & SCAN_AS_VENDOR) != 0)
10021                && SystemProperties.getInt("ro.vndk.version", 28) < 28;
10022        if (((scanFlags & SCAN_AS_PRIVILEGED) == 0)
10023                && !pkg.isPrivileged()
10024                && (pkg.mSharedUserId != null)
10025                && !skipVendorPrivilegeScan) {
10026            SharedUserSetting sharedUserSetting = null;
10027            try {
10028                sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
10029            } catch (PackageManagerException ignore) {}
10030            if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
10031                // Exempt SharedUsers signed with the platform key.
10032                // TODO(b/72378145) Fix this exemption. Force signature apps
10033                // to whitelist their privileged permissions just like other
10034                // priv-apps.
10035                synchronized (mPackages) {
10036                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
10037                    if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
10038                                pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
10039                        scanFlags |= SCAN_AS_PRIVILEGED;
10040                    }
10041                }
10042            }
10043        }
10044
10045        return scanFlags;
10046    }
10047
10048    // TODO: scanPackageNewLI() and scanPackageOnly() should be merged. But, first, commiting
10049    // the results / removing app data needs to be moved up a level to the callers of this
10050    // method. Also, we need to solve the problem of potentially creating a new shared user
10051    // setting. That can probably be done later and patch things up after the fact.
10052    @GuardedBy("mInstallLock")
10053    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
10054            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
10055            @Nullable UserHandle user) throws PackageManagerException {
10056
10057        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10058        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
10059        if (realPkgName != null) {
10060            ensurePackageRenamed(pkg, renamedPkgName);
10061        }
10062        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
10063        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10064        final PackageSetting disabledPkgSetting =
10065                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10066
10067        if (mTransferedPackages.contains(pkg.packageName)) {
10068            Slog.w(TAG, "Package " + pkg.packageName
10069                    + " was transferred to another, but its .apk remains");
10070        }
10071
10072        scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg);
10073        synchronized (mPackages) {
10074            applyPolicy(pkg, parseFlags, scanFlags, mPlatformPackage);
10075            assertPackageIsValid(pkg, parseFlags, scanFlags);
10076
10077            SharedUserSetting sharedUserSetting = null;
10078            if (pkg.mSharedUserId != null) {
10079                // SIDE EFFECTS; may potentially allocate a new shared user
10080                sharedUserSetting = mSettings.getSharedUserLPw(
10081                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10082                if (DEBUG_PACKAGE_SCANNING) {
10083                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10084                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
10085                                + " (uid=" + sharedUserSetting.userId + "):"
10086                                + " packages=" + sharedUserSetting.packages);
10087                }
10088            }
10089
10090            boolean scanSucceeded = false;
10091            try {
10092                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
10093                        pkgSetting == null ? null : pkgSetting.pkg, pkgSetting, disabledPkgSetting,
10094                        originalPkgSetting, realPkgName, parseFlags, scanFlags,
10095                        (pkg == mPlatformPackage), user);
10096                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
10097                if (result.success) {
10098                    commitScanResultsLocked(request, result);
10099                }
10100                scanSucceeded = true;
10101            } finally {
10102                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10103                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
10104                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10105                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10106                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10107                  }
10108            }
10109        }
10110        return pkg;
10111    }
10112
10113    /**
10114     * Commits the package scan and modifies system state.
10115     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
10116     * of committing the package, leaving the system in an inconsistent state.
10117     * This needs to be fixed so, once we get to this point, no errors are
10118     * possible and the system is not left in an inconsistent state.
10119     */
10120    @GuardedBy("mPackages")
10121    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
10122            throws PackageManagerException {
10123        final PackageParser.Package pkg = request.pkg;
10124        final PackageParser.Package oldPkg = request.oldPkg;
10125        final @ParseFlags int parseFlags = request.parseFlags;
10126        final @ScanFlags int scanFlags = request.scanFlags;
10127        final PackageSetting oldPkgSetting = request.oldPkgSetting;
10128        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10129        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10130        final UserHandle user = request.user;
10131        final String realPkgName = request.realPkgName;
10132        final PackageSetting pkgSetting = result.pkgSetting;
10133        final List<String> changedAbiCodePath = result.changedAbiCodePath;
10134        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
10135
10136        if (newPkgSettingCreated) {
10137            if (originalPkgSetting != null) {
10138                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
10139            }
10140            // THROWS: when we can't allocate a user id. add call to check if there's
10141            // enough space to ensure we won't throw; otherwise, don't modify state
10142            mSettings.addUserToSettingLPw(pkgSetting);
10143
10144            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
10145                mTransferedPackages.add(originalPkgSetting.name);
10146            }
10147        }
10148        // TODO(toddke): Consider a method specifically for modifying the Package object
10149        // post scan; or, moving this stuff out of the Package object since it has nothing
10150        // to do with the package on disk.
10151        // We need to have this here because addUserToSettingLPw() is sometimes responsible
10152        // for creating the application ID. If we did this earlier, we would be saving the
10153        // correct ID.
10154        pkg.applicationInfo.uid = pkgSetting.appId;
10155
10156        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10157
10158        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
10159            mTransferedPackages.add(pkg.packageName);
10160        }
10161
10162        // THROWS: when requested libraries that can't be found. it only changes
10163        // the state of the passed in pkg object, so, move to the top of the method
10164        // and allow it to abort
10165        if ((scanFlags & SCAN_BOOTING) == 0
10166                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10167            // Check all shared libraries and map to their actual file path.
10168            // We only do this here for apps not on a system dir, because those
10169            // are the only ones that can fail an install due to this.  We
10170            // will take care of the system apps by updating all of their
10171            // library paths after the scan is done. Also during the initial
10172            // scan don't update any libs as we do this wholesale after all
10173            // apps are scanned to avoid dependency based scanning.
10174            updateSharedLibrariesLPr(pkg, null);
10175        }
10176
10177        // All versions of a static shared library are referenced with the same
10178        // package name. Internally, we use a synthetic package name to allow
10179        // multiple versions of the same shared library to be installed. So,
10180        // we need to generate the synthetic package name of the latest shared
10181        // library in order to compare signatures.
10182        PackageSetting signatureCheckPs = pkgSetting;
10183        if (pkg.applicationInfo.isStaticSharedLibrary()) {
10184            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10185            if (libraryEntry != null) {
10186                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10187            }
10188        }
10189
10190        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10191        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
10192            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
10193                // We just determined the app is signed correctly, so bring
10194                // over the latest parsed certs.
10195                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10196            } else {
10197                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10198                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10199                            "Package " + pkg.packageName + " upgrade keys do not match the "
10200                                    + "previously installed version");
10201                } else {
10202                    pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10203                    String msg = "System package " + pkg.packageName
10204                            + " signature changed; retaining data.";
10205                    reportSettingsProblem(Log.WARN, msg);
10206                }
10207            }
10208        } else {
10209            try {
10210                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
10211                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
10212                final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting,
10213                        pkg.mSigningDetails, compareCompat, compareRecover);
10214                // The new KeySets will be re-added later in the scanning process.
10215                if (compatMatch) {
10216                    synchronized (mPackages) {
10217                        ksms.removeAppKeySetDataLPw(pkg.packageName);
10218                    }
10219                }
10220                // We just determined the app is signed correctly, so bring
10221                // over the latest parsed certs.
10222                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10223
10224
10225                // if this is is a sharedUser, check to see if the new package is signed by a newer
10226                // signing certificate than the existing one, and if so, copy over the new details
10227                if (signatureCheckPs.sharedUser != null) {
10228                    if (pkg.mSigningDetails.hasAncestor(
10229                                signatureCheckPs.sharedUser.signatures.mSigningDetails)) {
10230                        signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10231                    }
10232                    if (signatureCheckPs.sharedUser.signaturesChanged == null) {
10233                        signatureCheckPs.sharedUser.signaturesChanged = Boolean.FALSE;
10234                    }
10235                }
10236            } catch (PackageManagerException e) {
10237                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10238                    throw e;
10239                }
10240                // The signature has changed, but this package is in the system
10241                // image...  let's recover!
10242                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10243
10244                // If the system app is part of a shared user we allow that shared user to change
10245                // signatures as well as part of an OTA. We still need to verify that the signatures
10246                // are consistent within the shared user for a given boot, so only allow updating
10247                // the signatures on the first package scanned for the shared user (i.e. if the
10248                // signaturesChanged state hasn't been initialized yet in SharedUserSetting).
10249                if (signatureCheckPs.sharedUser != null) {
10250                    if (signatureCheckPs.sharedUser.signaturesChanged != null &&
10251                        compareSignatures(
10252                            signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures,
10253                            pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) {
10254                        throw new PackageManagerException(
10255                                INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10256                                "Signature mismatch for shared user: " + pkgSetting.sharedUser);
10257                    }
10258
10259                    signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10260                    signatureCheckPs.sharedUser.signaturesChanged = Boolean.TRUE;
10261                }
10262                // File a report about this.
10263                String msg = "System package " + pkg.packageName
10264                        + " signature changed; retaining data.";
10265                reportSettingsProblem(Log.WARN, msg);
10266            } catch (IllegalArgumentException e) {
10267
10268                // should never happen: certs matched when checking, but not when comparing
10269                // old to new for sharedUser
10270                throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10271                        "Signing certificates comparison made on incomparable signing details"
10272                        + " but somehow passed verifySignatures!");
10273            }
10274        }
10275
10276        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10277            // This package wants to adopt ownership of permissions from
10278            // another package.
10279            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10280                final String origName = pkg.mAdoptPermissions.get(i);
10281                final PackageSetting orig = mSettings.getPackageLPr(origName);
10282                if (orig != null) {
10283                    if (verifyPackageUpdateLPr(orig, pkg)) {
10284                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
10285                                + pkg.packageName);
10286                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10287                    }
10288                }
10289            }
10290        }
10291
10292        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
10293            for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
10294                final String codePathString = changedAbiCodePath.get(i);
10295                try {
10296                    mInstaller.rmdex(codePathString,
10297                            getDexCodeInstructionSet(getPreferredInstructionSet()));
10298                } catch (InstallerException ignored) {
10299                }
10300            }
10301        }
10302
10303        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10304            if (oldPkgSetting != null) {
10305                synchronized (mPackages) {
10306                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
10307                }
10308            }
10309        } else {
10310            final int userId = user == null ? 0 : user.getIdentifier();
10311            // Modify state for the given package setting
10312            commitPackageSettings(pkg, oldPkg, pkgSetting, user, scanFlags,
10313                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10314            if (pkgSetting.getInstantApp(userId)) {
10315                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10316            }
10317        }
10318    }
10319
10320    /**
10321     * Returns the "real" name of the package.
10322     * <p>This may differ from the package's actual name if the application has already
10323     * been installed under one of this package's original names.
10324     */
10325    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
10326            @Nullable String renamedPkgName) {
10327        if (isPackageRenamed(pkg, renamedPkgName)) {
10328            return pkg.mRealPackage;
10329        }
10330        return null;
10331    }
10332
10333    /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
10334    private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
10335            @Nullable String renamedPkgName) {
10336        return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
10337    }
10338
10339    /**
10340     * Returns the original package setting.
10341     * <p>A package can migrate its name during an update. In this scenario, a package
10342     * designates a set of names that it considers as one of its original names.
10343     * <p>An original package must be signed identically and it must have the same
10344     * shared user [if any].
10345     */
10346    @GuardedBy("mPackages")
10347    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
10348            @Nullable String renamedPkgName) {
10349        if (!isPackageRenamed(pkg, renamedPkgName)) {
10350            return null;
10351        }
10352        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
10353            final PackageSetting originalPs =
10354                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
10355            if (originalPs != null) {
10356                // the package is already installed under its original name...
10357                // but, should we use it?
10358                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
10359                    // the new package is incompatible with the original
10360                    continue;
10361                } else if (originalPs.sharedUser != null) {
10362                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
10363                        // the shared user id is incompatible with the original
10364                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
10365                                + " to " + pkg.packageName + ": old uid "
10366                                + originalPs.sharedUser.name
10367                                + " differs from " + pkg.mSharedUserId);
10368                        continue;
10369                    }
10370                    // TODO: Add case when shared user id is added [b/28144775]
10371                } else {
10372                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10373                            + pkg.packageName + " to old name " + originalPs.name);
10374                }
10375                return originalPs;
10376            }
10377        }
10378        return null;
10379    }
10380
10381    /**
10382     * Renames the package if it was installed under a different name.
10383     * <p>When we've already installed the package under an original name, update
10384     * the new package so we can continue to have the old name.
10385     */
10386    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10387            @NonNull String renamedPackageName) {
10388        if (pkg.mOriginalPackages == null
10389                || !pkg.mOriginalPackages.contains(renamedPackageName)
10390                || pkg.packageName.equals(renamedPackageName)) {
10391            return;
10392        }
10393        pkg.setPackageName(renamedPackageName);
10394    }
10395
10396    /**
10397     * Just scans the package without any side effects.
10398     * <p>Not entirely true at the moment. There is still one side effect -- this
10399     * method potentially modifies a live {@link PackageSetting} object representing
10400     * the package being scanned. This will be resolved in the future.
10401     *
10402     * @param request Information about the package to be scanned
10403     * @param isUnderFactoryTest Whether or not the device is under factory test
10404     * @param currentTime The current time, in millis
10405     * @return The results of the scan
10406     */
10407    @GuardedBy("mInstallLock")
10408    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10409            boolean isUnderFactoryTest, long currentTime)
10410                    throws PackageManagerException {
10411        final PackageParser.Package pkg = request.pkg;
10412        PackageSetting pkgSetting = request.pkgSetting;
10413        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10414        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10415        final @ParseFlags int parseFlags = request.parseFlags;
10416        final @ScanFlags int scanFlags = request.scanFlags;
10417        final String realPkgName = request.realPkgName;
10418        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10419        final UserHandle user = request.user;
10420        final boolean isPlatformPackage = request.isPlatformPackage;
10421
10422        List<String> changedAbiCodePath = null;
10423
10424        if (DEBUG_PACKAGE_SCANNING) {
10425            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10426                Log.d(TAG, "Scanning package " + pkg.packageName);
10427        }
10428
10429        DexManager.maybeLogUnexpectedPackageDetails(pkg);
10430
10431        // Initialize package source and resource directories
10432        final File scanFile = new File(pkg.codePath);
10433        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10434        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10435
10436        // We keep references to the derived CPU Abis from settings in oder to reuse
10437        // them in the case where we're not upgrading or booting for the first time.
10438        String primaryCpuAbiFromSettings = null;
10439        String secondaryCpuAbiFromSettings = null;
10440        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10441
10442        if (!needToDeriveAbi) {
10443            if (pkgSetting != null) {
10444                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10445                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10446            } else {
10447                // Re-scanning a system package after uninstalling updates; need to derive ABI
10448                needToDeriveAbi = true;
10449            }
10450        }
10451
10452        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10453            PackageManagerService.reportSettingsProblem(Log.WARN,
10454                    "Package " + pkg.packageName + " shared user changed from "
10455                            + (pkgSetting.sharedUser != null
10456                            ? pkgSetting.sharedUser.name : "<nothing>")
10457                            + " to "
10458                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10459                            + "; replacing with new");
10460            pkgSetting = null;
10461        }
10462
10463        String[] usesStaticLibraries = null;
10464        if (pkg.usesStaticLibraries != null) {
10465            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10466            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10467        }
10468        final boolean createNewPackage = (pkgSetting == null);
10469        if (createNewPackage) {
10470            final String parentPackageName = (pkg.parentPackage != null)
10471                    ? pkg.parentPackage.packageName : null;
10472            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10473            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10474            // REMOVE SharedUserSetting from method; update in a separate call
10475            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10476                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10477                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10478                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10479                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10480                    user, true /*allowInstall*/, instantApp, virtualPreload,
10481                    parentPackageName, pkg.getChildPackageNames(),
10482                    UserManagerService.getInstance(), usesStaticLibraries,
10483                    pkg.usesStaticLibrariesVersions);
10484        } else {
10485            // REMOVE SharedUserSetting from method; update in a separate call.
10486            //
10487            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10488            // secondaryCpuAbi are not known at this point so we always update them
10489            // to null here, only to reset them at a later point.
10490            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10491                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
10492                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10493                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10494                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10495                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10496        }
10497        if (createNewPackage && originalPkgSetting != null) {
10498            // This is the initial transition from the original package, so,
10499            // fix up the new package's name now. We must do this after looking
10500            // up the package under its new name, so getPackageLP takes care of
10501            // fiddling things correctly.
10502            pkg.setPackageName(originalPkgSetting.name);
10503
10504            // File a report about this.
10505            String msg = "New package " + pkgSetting.realName
10506                    + " renamed to replace old package " + pkgSetting.name;
10507            reportSettingsProblem(Log.WARN, msg);
10508        }
10509
10510        final int userId = (user == null ? UserHandle.USER_SYSTEM : user.getIdentifier());
10511        // for existing packages, change the install state; but, only if it's explicitly specified
10512        if (!createNewPackage) {
10513            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10514            final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
10515            setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
10516        }
10517
10518        if (disabledPkgSetting != null) {
10519            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10520        }
10521
10522        // Apps which share a sharedUserId must be placed in the same selinux domain. If this
10523        // package is the first app installed as this shared user, set seInfoTargetSdkVersion to its
10524        // targetSdkVersion. These are later adjusted in PackageManagerService's constructor to be
10525        // the lowest targetSdkVersion of all apps within the shared user, which corresponds to the
10526        // least restrictive selinux domain.
10527        // NOTE: As new packages are installed / updated, the shared user's seinfoTargetSdkVersion
10528        // will NOT be modified until next boot, even if a lower targetSdkVersion is used. This
10529        // ensures that all packages continue to run in the same selinux domain.
10530        final int targetSdkVersion =
10531            ((sharedUserSetting != null) && (sharedUserSetting.packages.size() != 0)) ?
10532            sharedUserSetting.seInfoTargetSdkVersion : pkg.applicationInfo.targetSdkVersion;
10533        // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync.
10534        // They currently can be if the sharedUser apps are signed with the platform key.
10535        final boolean isPrivileged = (sharedUserSetting != null) ?
10536            sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged();
10537
10538        pkg.applicationInfo.seInfo = SELinuxMMAC.getSeInfo(pkg, isPrivileged,
10539                pkg.applicationInfo.targetSandboxVersion, targetSdkVersion);
10540        pkg.applicationInfo.seInfoUser = SELinuxUtil.assignSeinfoUser(pkgSetting.readUserState(
10541                userId == UserHandle.USER_ALL ? UserHandle.USER_SYSTEM : userId));
10542
10543        pkg.mExtras = pkgSetting;
10544        pkg.applicationInfo.processName = fixProcessName(
10545                pkg.applicationInfo.packageName,
10546                pkg.applicationInfo.processName);
10547
10548        if (!isPlatformPackage) {
10549            // Get all of our default paths setup
10550            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10551        }
10552
10553        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10554
10555        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10556            if (needToDeriveAbi) {
10557                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10558                final boolean extractNativeLibs = !pkg.isLibrary();
10559                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10560                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10561
10562                // Some system apps still use directory structure for native libraries
10563                // in which case we might end up not detecting abi solely based on apk
10564                // structure. Try to detect abi based on directory structure.
10565                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10566                        pkg.applicationInfo.primaryCpuAbi == null) {
10567                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10568                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10569                }
10570            } else {
10571                // This is not a first boot or an upgrade, don't bother deriving the
10572                // ABI during the scan. Instead, trust the value that was stored in the
10573                // package setting.
10574                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10575                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10576
10577                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10578
10579                if (DEBUG_ABI_SELECTION) {
10580                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10581                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10582                            pkg.applicationInfo.secondaryCpuAbi);
10583                }
10584            }
10585        } else {
10586            if ((scanFlags & SCAN_MOVE) != 0) {
10587                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10588                // but we already have this packages package info in the PackageSetting. We just
10589                // use that and derive the native library path based on the new codepath.
10590                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10591                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10592            }
10593
10594            // Set native library paths again. For moves, the path will be updated based on the
10595            // ABIs we've determined above. For non-moves, the path will be updated based on the
10596            // ABIs we determined during compilation, but the path will depend on the final
10597            // package path (after the rename away from the stage path).
10598            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10599        }
10600
10601        // This is a special case for the "system" package, where the ABI is
10602        // dictated by the zygote configuration (and init.rc). We should keep track
10603        // of this ABI so that we can deal with "normal" applications that run under
10604        // the same UID correctly.
10605        if (isPlatformPackage) {
10606            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10607                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10608        }
10609
10610        // If there's a mismatch between the abi-override in the package setting
10611        // and the abiOverride specified for the install. Warn about this because we
10612        // would've already compiled the app without taking the package setting into
10613        // account.
10614        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10615            if (cpuAbiOverride == null && pkg.packageName != null) {
10616                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10617                        " for package " + pkg.packageName);
10618            }
10619        }
10620
10621        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10622        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10623        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10624
10625        // Copy the derived override back to the parsed package, so that we can
10626        // update the package settings accordingly.
10627        pkg.cpuAbiOverride = cpuAbiOverride;
10628
10629        if (DEBUG_ABI_SELECTION) {
10630            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
10631                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10632                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10633        }
10634
10635        // Push the derived path down into PackageSettings so we know what to
10636        // clean up at uninstall time.
10637        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10638
10639        if (DEBUG_ABI_SELECTION) {
10640            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10641                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10642                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10643        }
10644
10645        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10646            // We don't do this here during boot because we can do it all
10647            // at once after scanning all existing packages.
10648            //
10649            // We also do this *before* we perform dexopt on this package, so that
10650            // we can avoid redundant dexopts, and also to make sure we've got the
10651            // code and package path correct.
10652            changedAbiCodePath =
10653                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10654        }
10655
10656        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10657                android.Manifest.permission.FACTORY_TEST)) {
10658            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10659        }
10660
10661        if (isSystemApp(pkg)) {
10662            pkgSetting.isOrphaned = true;
10663        }
10664
10665        // Take care of first install / last update times.
10666        final long scanFileTime = getLastModifiedTime(pkg);
10667        if (currentTime != 0) {
10668            if (pkgSetting.firstInstallTime == 0) {
10669                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10670            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10671                pkgSetting.lastUpdateTime = currentTime;
10672            }
10673        } else if (pkgSetting.firstInstallTime == 0) {
10674            // We need *something*.  Take time time stamp of the file.
10675            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10676        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10677            if (scanFileTime != pkgSetting.timeStamp) {
10678                // A package on the system image has changed; consider this
10679                // to be an update.
10680                pkgSetting.lastUpdateTime = scanFileTime;
10681            }
10682        }
10683        pkgSetting.setTimeStamp(scanFileTime);
10684
10685        pkgSetting.pkg = pkg;
10686        pkgSetting.pkgFlags = pkg.applicationInfo.flags;
10687        if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
10688            pkgSetting.versionCode = pkg.getLongVersionCode();
10689        }
10690        // Update volume if needed
10691        final String volumeUuid = pkg.applicationInfo.volumeUuid;
10692        if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
10693            Slog.i(PackageManagerService.TAG,
10694                    "Update" + (pkgSetting.isSystem() ? " system" : "")
10695                    + " package " + pkg.packageName
10696                    + " volume from " + pkgSetting.volumeUuid
10697                    + " to " + volumeUuid);
10698            pkgSetting.volumeUuid = volumeUuid;
10699        }
10700
10701        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10702    }
10703
10704    /**
10705     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10706     */
10707    private static boolean apkHasCode(String fileName) {
10708        StrictJarFile jarFile = null;
10709        try {
10710            jarFile = new StrictJarFile(fileName,
10711                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10712            return jarFile.findEntry("classes.dex") != null;
10713        } catch (IOException ignore) {
10714        } finally {
10715            try {
10716                if (jarFile != null) {
10717                    jarFile.close();
10718                }
10719            } catch (IOException ignore) {}
10720        }
10721        return false;
10722    }
10723
10724    /**
10725     * Enforces code policy for the package. This ensures that if an APK has
10726     * declared hasCode="true" in its manifest that the APK actually contains
10727     * code.
10728     *
10729     * @throws PackageManagerException If bytecode could not be found when it should exist
10730     */
10731    private static void assertCodePolicy(PackageParser.Package pkg)
10732            throws PackageManagerException {
10733        final boolean shouldHaveCode =
10734                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10735        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10736            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10737                    "Package " + pkg.baseCodePath + " code is missing");
10738        }
10739
10740        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10741            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10742                final boolean splitShouldHaveCode =
10743                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10744                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10745                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10746                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10747                }
10748            }
10749        }
10750    }
10751
10752    /**
10753     * Applies policy to the parsed package based upon the given policy flags.
10754     * Ensures the package is in a good state.
10755     * <p>
10756     * Implementation detail: This method must NOT have any side effect. It would
10757     * ideally be static, but, it requires locks to read system state.
10758     */
10759    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10760            final @ScanFlags int scanFlags, PackageParser.Package platformPkg) {
10761        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10762            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10763            if (pkg.applicationInfo.isDirectBootAware()) {
10764                // we're direct boot aware; set for all components
10765                for (PackageParser.Service s : pkg.services) {
10766                    s.info.encryptionAware = s.info.directBootAware = true;
10767                }
10768                for (PackageParser.Provider p : pkg.providers) {
10769                    p.info.encryptionAware = p.info.directBootAware = true;
10770                }
10771                for (PackageParser.Activity a : pkg.activities) {
10772                    a.info.encryptionAware = a.info.directBootAware = true;
10773                }
10774                for (PackageParser.Activity r : pkg.receivers) {
10775                    r.info.encryptionAware = r.info.directBootAware = true;
10776                }
10777            }
10778            if (compressedFileExists(pkg.codePath)) {
10779                pkg.isStub = true;
10780            }
10781        } else {
10782            // non system apps can't be flagged as core
10783            pkg.coreApp = false;
10784            // clear flags not applicable to regular apps
10785            pkg.applicationInfo.flags &=
10786                    ~ApplicationInfo.FLAG_PERSISTENT;
10787            pkg.applicationInfo.privateFlags &=
10788                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10789            pkg.applicationInfo.privateFlags &=
10790                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10791            // cap permission priorities
10792            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10793                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10794                    pkg.permissionGroups.get(i).info.priority = 0;
10795                }
10796            }
10797        }
10798        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10799            // clear protected broadcasts
10800            pkg.protectedBroadcasts = null;
10801            // ignore export request for single user receivers
10802            if (pkg.receivers != null) {
10803                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10804                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10805                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10806                        receiver.info.exported = false;
10807                    }
10808                }
10809            }
10810            // ignore export request for single user services
10811            if (pkg.services != null) {
10812                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10813                    final PackageParser.Service service = pkg.services.get(i);
10814                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10815                        service.info.exported = false;
10816                    }
10817                }
10818            }
10819            // ignore export request for single user providers
10820            if (pkg.providers != null) {
10821                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10822                    final PackageParser.Provider provider = pkg.providers.get(i);
10823                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10824                        provider.info.exported = false;
10825                    }
10826                }
10827            }
10828        }
10829
10830        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10831            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10832        }
10833
10834        if ((scanFlags & SCAN_AS_OEM) != 0) {
10835            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10836        }
10837
10838        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10839            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10840        }
10841
10842        if ((scanFlags & SCAN_AS_PRODUCT) != 0) {
10843            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT;
10844        }
10845
10846        // Check if the package is signed with the same key as the platform package.
10847        if (PLATFORM_PACKAGE_NAME.equals(pkg.packageName) ||
10848                (platformPkg != null && compareSignatures(
10849                        platformPkg.mSigningDetails.signatures,
10850                        pkg.mSigningDetails.signatures) == PackageManager.SIGNATURE_MATCH)) {
10851            pkg.applicationInfo.privateFlags |=
10852                ApplicationInfo.PRIVATE_FLAG_SIGNED_WITH_PLATFORM_KEY;
10853        }
10854
10855        if (!isSystemApp(pkg)) {
10856            // Only system apps can use these features.
10857            pkg.mOriginalPackages = null;
10858            pkg.mRealPackage = null;
10859            pkg.mAdoptPermissions = null;
10860        }
10861    }
10862
10863    private static @NonNull <T> T assertNotNull(@Nullable T object, String message)
10864            throws PackageManagerException {
10865        if (object == null) {
10866            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message);
10867        }
10868        return object;
10869    }
10870
10871    /**
10872     * Asserts the parsed package is valid according to the given policy. If the
10873     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10874     * <p>
10875     * Implementation detail: This method must NOT have any side effects. It would
10876     * ideally be static, but, it requires locks to read system state.
10877     *
10878     * @throws PackageManagerException If the package fails any of the validation checks
10879     */
10880    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10881            final @ScanFlags int scanFlags)
10882                    throws PackageManagerException {
10883        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10884            assertCodePolicy(pkg);
10885        }
10886
10887        if (pkg.applicationInfo.getCodePath() == null ||
10888                pkg.applicationInfo.getResourcePath() == null) {
10889            // Bail out. The resource and code paths haven't been set.
10890            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10891                    "Code and resource paths haven't been set correctly");
10892        }
10893
10894        // Make sure we're not adding any bogus keyset info
10895        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10896        ksms.assertScannedPackageValid(pkg);
10897
10898        synchronized (mPackages) {
10899            // The special "android" package can only be defined once
10900            if (pkg.packageName.equals("android")) {
10901                if (mAndroidApplication != null) {
10902                    Slog.w(TAG, "*************************************************");
10903                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10904                    Slog.w(TAG, " codePath=" + pkg.codePath);
10905                    Slog.w(TAG, "*************************************************");
10906                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10907                            "Core android package being redefined.  Skipping.");
10908                }
10909            }
10910
10911            // A package name must be unique; don't allow duplicates
10912            if (mPackages.containsKey(pkg.packageName)) {
10913                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10914                        "Application package " + pkg.packageName
10915                        + " already installed.  Skipping duplicate.");
10916            }
10917
10918            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10919                // Static libs have a synthetic package name containing the version
10920                // but we still want the base name to be unique.
10921                if (mPackages.containsKey(pkg.manifestPackageName)) {
10922                    throw new PackageManagerException(
10923                            "Duplicate static shared lib provider package");
10924                }
10925
10926                // Static shared libraries should have at least O target SDK
10927                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10928                    throw new PackageManagerException(
10929                            "Packages declaring static-shared libs must target O SDK or higher");
10930                }
10931
10932                // Package declaring static a shared lib cannot be instant apps
10933                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10934                    throw new PackageManagerException(
10935                            "Packages declaring static-shared libs cannot be instant apps");
10936                }
10937
10938                // Package declaring static a shared lib cannot be renamed since the package
10939                // name is synthetic and apps can't code around package manager internals.
10940                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10941                    throw new PackageManagerException(
10942                            "Packages declaring static-shared libs cannot be renamed");
10943                }
10944
10945                // Package declaring static a shared lib cannot declare child packages
10946                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10947                    throw new PackageManagerException(
10948                            "Packages declaring static-shared libs cannot have child packages");
10949                }
10950
10951                // Package declaring static a shared lib cannot declare dynamic libs
10952                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10953                    throw new PackageManagerException(
10954                            "Packages declaring static-shared libs cannot declare dynamic libs");
10955                }
10956
10957                // Package declaring static a shared lib cannot declare shared users
10958                if (pkg.mSharedUserId != null) {
10959                    throw new PackageManagerException(
10960                            "Packages declaring static-shared libs cannot declare shared users");
10961                }
10962
10963                // Static shared libs cannot declare activities
10964                if (!pkg.activities.isEmpty()) {
10965                    throw new PackageManagerException(
10966                            "Static shared libs cannot declare activities");
10967                }
10968
10969                // Static shared libs cannot declare services
10970                if (!pkg.services.isEmpty()) {
10971                    throw new PackageManagerException(
10972                            "Static shared libs cannot declare services");
10973                }
10974
10975                // Static shared libs cannot declare providers
10976                if (!pkg.providers.isEmpty()) {
10977                    throw new PackageManagerException(
10978                            "Static shared libs cannot declare content providers");
10979                }
10980
10981                // Static shared libs cannot declare receivers
10982                if (!pkg.receivers.isEmpty()) {
10983                    throw new PackageManagerException(
10984                            "Static shared libs cannot declare broadcast receivers");
10985                }
10986
10987                // Static shared libs cannot declare permission groups
10988                if (!pkg.permissionGroups.isEmpty()) {
10989                    throw new PackageManagerException(
10990                            "Static shared libs cannot declare permission groups");
10991                }
10992
10993                // Static shared libs cannot declare permissions
10994                if (!pkg.permissions.isEmpty()) {
10995                    throw new PackageManagerException(
10996                            "Static shared libs cannot declare permissions");
10997                }
10998
10999                // Static shared libs cannot declare protected broadcasts
11000                if (pkg.protectedBroadcasts != null) {
11001                    throw new PackageManagerException(
11002                            "Static shared libs cannot declare protected broadcasts");
11003                }
11004
11005                // Static shared libs cannot be overlay targets
11006                if (pkg.mOverlayTarget != null) {
11007                    throw new PackageManagerException(
11008                            "Static shared libs cannot be overlay targets");
11009                }
11010
11011                // The version codes must be ordered as lib versions
11012                long minVersionCode = Long.MIN_VALUE;
11013                long maxVersionCode = Long.MAX_VALUE;
11014
11015                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
11016                        pkg.staticSharedLibName);
11017                if (versionedLib != null) {
11018                    final int versionCount = versionedLib.size();
11019                    for (int i = 0; i < versionCount; i++) {
11020                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
11021                        final long libVersionCode = libInfo.getDeclaringPackage()
11022                                .getLongVersionCode();
11023                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
11024                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
11025                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
11026                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
11027                        } else {
11028                            minVersionCode = maxVersionCode = libVersionCode;
11029                            break;
11030                        }
11031                    }
11032                }
11033                if (pkg.getLongVersionCode() < minVersionCode
11034                        || pkg.getLongVersionCode() > maxVersionCode) {
11035                    throw new PackageManagerException("Static shared"
11036                            + " lib version codes must be ordered as lib versions");
11037                }
11038            }
11039
11040            // Only privileged apps and updated privileged apps can add child packages.
11041            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
11042                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
11043                    throw new PackageManagerException("Only privileged apps can add child "
11044                            + "packages. Ignoring package " + pkg.packageName);
11045                }
11046                final int childCount = pkg.childPackages.size();
11047                for (int i = 0; i < childCount; i++) {
11048                    PackageParser.Package childPkg = pkg.childPackages.get(i);
11049                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
11050                            childPkg.packageName)) {
11051                        throw new PackageManagerException("Can't override child of "
11052                                + "another disabled app. Ignoring package " + pkg.packageName);
11053                    }
11054                }
11055            }
11056
11057            // If we're only installing presumed-existing packages, require that the
11058            // scanned APK is both already known and at the path previously established
11059            // for it.  Previously unknown packages we pick up normally, but if we have an
11060            // a priori expectation about this package's install presence, enforce it.
11061            // With a singular exception for new system packages. When an OTA contains
11062            // a new system package, we allow the codepath to change from a system location
11063            // to the user-installed location. If we don't allow this change, any newer,
11064            // user-installed version of the application will be ignored.
11065            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11066                if (mExpectingBetter.containsKey(pkg.packageName)) {
11067                    logCriticalInfo(Log.WARN,
11068                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11069                } else {
11070                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11071                    if (known != null) {
11072                        if (DEBUG_PACKAGE_SCANNING) {
11073                            Log.d(TAG, "Examining " + pkg.codePath
11074                                    + " and requiring known paths " + known.codePathString
11075                                    + " & " + known.resourcePathString);
11076                        }
11077                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11078                                || !pkg.applicationInfo.getResourcePath().equals(
11079                                        known.resourcePathString)) {
11080                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11081                                    "Application package " + pkg.packageName
11082                                    + " found at " + pkg.applicationInfo.getCodePath()
11083                                    + " but expected at " + known.codePathString
11084                                    + "; ignoring.");
11085                        }
11086                    } else {
11087                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11088                                "Application package " + pkg.packageName
11089                                + " not found; ignoring.");
11090                    }
11091                }
11092            }
11093
11094            // Verify that this new package doesn't have any content providers
11095            // that conflict with existing packages.  Only do this if the
11096            // package isn't already installed, since we don't want to break
11097            // things that are installed.
11098            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11099                final int N = pkg.providers.size();
11100                int i;
11101                for (i=0; i<N; i++) {
11102                    PackageParser.Provider p = pkg.providers.get(i);
11103                    if (p.info.authority != null) {
11104                        String names[] = p.info.authority.split(";");
11105                        for (int j = 0; j < names.length; j++) {
11106                            if (mProvidersByAuthority.containsKey(names[j])) {
11107                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11108                                final String otherPackageName =
11109                                        ((other != null && other.getComponentName() != null) ?
11110                                                other.getComponentName().getPackageName() : "?");
11111                                throw new PackageManagerException(
11112                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11113                                        "Can't install because provider name " + names[j]
11114                                                + " (in package " + pkg.applicationInfo.packageName
11115                                                + ") is already used by " + otherPackageName);
11116                            }
11117                        }
11118                    }
11119                }
11120            }
11121
11122            // Verify that packages sharing a user with a privileged app are marked as privileged.
11123            if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
11124                SharedUserSetting sharedUserSetting = null;
11125                try {
11126                    sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
11127                } catch (PackageManagerException ignore) {}
11128                if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
11129                    // Exempt SharedUsers signed with the platform key.
11130                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
11131                    if ((platformPkgSetting.signatures.mSigningDetails
11132                            != PackageParser.SigningDetails.UNKNOWN)
11133                            && (compareSignatures(
11134                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11135                                    pkg.mSigningDetails.signatures)
11136                                            != PackageManager.SIGNATURE_MATCH)) {
11137                        throw new PackageManagerException("Apps that share a user with a " +
11138                                "privileged app must themselves be marked as privileged. " +
11139                                pkg.packageName + " shares privileged user " +
11140                                pkg.mSharedUserId + ".");
11141                    }
11142                }
11143            }
11144
11145            // Apply policies specific for runtime resource overlays (RROs).
11146            if (pkg.mOverlayTarget != null) {
11147                // System overlays have some restrictions on their use of the 'static' state.
11148                if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
11149                    // We are scanning a system overlay. This can be the first scan of the
11150                    // system/vendor/oem partition, or an update to the system overlay.
11151                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
11152                        // This must be an update to a system overlay.
11153                        final PackageSetting previousPkg = assertNotNull(
11154                                mSettings.getPackageLPr(pkg.packageName),
11155                                "previous package state not present");
11156
11157                        // Static overlays cannot be updated.
11158                        if (previousPkg.pkg.mOverlayIsStatic) {
11159                            throw new PackageManagerException("Overlay " + pkg.packageName +
11160                                    " is static and cannot be upgraded.");
11161                        // Non-static overlays cannot be converted to static overlays.
11162                        } else if (pkg.mOverlayIsStatic) {
11163                            throw new PackageManagerException("Overlay " + pkg.packageName +
11164                                    " cannot be upgraded into a static overlay.");
11165                        }
11166                    }
11167                } else {
11168                    // The overlay is a non-system overlay. Non-system overlays cannot be static.
11169                    if (pkg.mOverlayIsStatic) {
11170                        throw new PackageManagerException("Overlay " + pkg.packageName +
11171                                " is static but not pre-installed.");
11172                    }
11173
11174                    // The only case where we allow installation of a non-system overlay is when
11175                    // its signature is signed with the platform certificate.
11176                    PackageSetting platformPkgSetting = mSettings.getPackageLPr("android");
11177                    if ((platformPkgSetting.signatures.mSigningDetails
11178                            != PackageParser.SigningDetails.UNKNOWN)
11179                            && (compareSignatures(
11180                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11181                                    pkg.mSigningDetails.signatures)
11182                                            != PackageManager.SIGNATURE_MATCH)) {
11183                        throw new PackageManagerException("Overlay " + pkg.packageName +
11184                                " must be signed with the platform certificate.");
11185                    }
11186                }
11187            }
11188        }
11189    }
11190
11191    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
11192            int type, String declaringPackageName, long declaringVersionCode) {
11193        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11194        if (versionedLib == null) {
11195            versionedLib = new LongSparseArray<>();
11196            mSharedLibraries.put(name, versionedLib);
11197            if (type == SharedLibraryInfo.TYPE_STATIC) {
11198                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11199            }
11200        } else if (versionedLib.indexOfKey(version) >= 0) {
11201            return false;
11202        }
11203        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11204                version, type, declaringPackageName, declaringVersionCode);
11205        versionedLib.put(version, libEntry);
11206        return true;
11207    }
11208
11209    private boolean removeSharedLibraryLPw(String name, long version) {
11210        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11211        if (versionedLib == null) {
11212            return false;
11213        }
11214        final int libIdx = versionedLib.indexOfKey(version);
11215        if (libIdx < 0) {
11216            return false;
11217        }
11218        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11219        versionedLib.remove(version);
11220        if (versionedLib.size() <= 0) {
11221            mSharedLibraries.remove(name);
11222            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11223                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11224                        .getPackageName());
11225            }
11226        }
11227        return true;
11228    }
11229
11230    /**
11231     * Adds a scanned package to the system. When this method is finished, the package will
11232     * be available for query, resolution, etc...
11233     */
11234    private void commitPackageSettings(PackageParser.Package pkg,
11235            @Nullable PackageParser.Package oldPkg, PackageSetting pkgSetting, UserHandle user,
11236            final @ScanFlags int scanFlags, boolean chatty) {
11237        final String pkgName = pkg.packageName;
11238        if (mCustomResolverComponentName != null &&
11239                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11240            setUpCustomResolverActivity(pkg);
11241        }
11242
11243        if (pkg.packageName.equals("android")) {
11244            synchronized (mPackages) {
11245                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11246                    // Set up information for our fall-back user intent resolution activity.
11247                    mPlatformPackage = pkg;
11248                    pkg.mVersionCode = mSdkVersion;
11249                    pkg.mVersionCodeMajor = 0;
11250                    mAndroidApplication = pkg.applicationInfo;
11251                    if (!mResolverReplaced) {
11252                        mResolveActivity.applicationInfo = mAndroidApplication;
11253                        mResolveActivity.name = ResolverActivity.class.getName();
11254                        mResolveActivity.packageName = mAndroidApplication.packageName;
11255                        mResolveActivity.processName = "system:ui";
11256                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11257                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11258                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11259                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11260                        mResolveActivity.exported = true;
11261                        mResolveActivity.enabled = true;
11262                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11263                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11264                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11265                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11266                                | ActivityInfo.CONFIG_ORIENTATION
11267                                | ActivityInfo.CONFIG_KEYBOARD
11268                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11269                        mResolveInfo.activityInfo = mResolveActivity;
11270                        mResolveInfo.priority = 0;
11271                        mResolveInfo.preferredOrder = 0;
11272                        mResolveInfo.match = 0;
11273                        mResolveComponentName = new ComponentName(
11274                                mAndroidApplication.packageName, mResolveActivity.name);
11275                    }
11276                }
11277            }
11278        }
11279
11280        ArrayList<PackageParser.Package> clientLibPkgs = null;
11281        // writer
11282        synchronized (mPackages) {
11283            boolean hasStaticSharedLibs = false;
11284
11285            // Any app can add new static shared libraries
11286            if (pkg.staticSharedLibName != null) {
11287                // Static shared libs don't allow renaming as they have synthetic package
11288                // names to allow install of multiple versions, so use name from manifest.
11289                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11290                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11291                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
11292                    hasStaticSharedLibs = true;
11293                } else {
11294                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11295                                + pkg.staticSharedLibName + " already exists; skipping");
11296                }
11297                // Static shared libs cannot be updated once installed since they
11298                // use synthetic package name which includes the version code, so
11299                // not need to update other packages's shared lib dependencies.
11300            }
11301
11302            if (!hasStaticSharedLibs
11303                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11304                // Only system apps can add new dynamic shared libraries.
11305                if (pkg.libraryNames != null) {
11306                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11307                        String name = pkg.libraryNames.get(i);
11308                        boolean allowed = false;
11309                        if (pkg.isUpdatedSystemApp()) {
11310                            // New library entries can only be added through the
11311                            // system image.  This is important to get rid of a lot
11312                            // of nasty edge cases: for example if we allowed a non-
11313                            // system update of the app to add a library, then uninstalling
11314                            // the update would make the library go away, and assumptions
11315                            // we made such as through app install filtering would now
11316                            // have allowed apps on the device which aren't compatible
11317                            // with it.  Better to just have the restriction here, be
11318                            // conservative, and create many fewer cases that can negatively
11319                            // impact the user experience.
11320                            final PackageSetting sysPs = mSettings
11321                                    .getDisabledSystemPkgLPr(pkg.packageName);
11322                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11323                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11324                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11325                                        allowed = true;
11326                                        break;
11327                                    }
11328                                }
11329                            }
11330                        } else {
11331                            allowed = true;
11332                        }
11333                        if (allowed) {
11334                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11335                                    SharedLibraryInfo.VERSION_UNDEFINED,
11336                                    SharedLibraryInfo.TYPE_DYNAMIC,
11337                                    pkg.packageName, pkg.getLongVersionCode())) {
11338                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11339                                        + name + " already exists; skipping");
11340                            }
11341                        } else {
11342                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11343                                    + name + " that is not declared on system image; skipping");
11344                        }
11345                    }
11346
11347                    if ((scanFlags & SCAN_BOOTING) == 0) {
11348                        // If we are not booting, we need to update any applications
11349                        // that are clients of our shared library.  If we are booting,
11350                        // this will all be done once the scan is complete.
11351                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11352                    }
11353                }
11354            }
11355        }
11356
11357        if ((scanFlags & SCAN_BOOTING) != 0) {
11358            // No apps can run during boot scan, so they don't need to be frozen
11359        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11360            // Caller asked to not kill app, so it's probably not frozen
11361        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11362            // Caller asked us to ignore frozen check for some reason; they
11363            // probably didn't know the package name
11364        } else {
11365            // We're doing major surgery on this package, so it better be frozen
11366            // right now to keep it from launching
11367            checkPackageFrozen(pkgName);
11368        }
11369
11370        // Also need to kill any apps that are dependent on the library.
11371        if (clientLibPkgs != null) {
11372            for (int i=0; i<clientLibPkgs.size(); i++) {
11373                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11374                killApplication(clientPkg.applicationInfo.packageName,
11375                        clientPkg.applicationInfo.uid, "update lib");
11376            }
11377        }
11378
11379        // writer
11380        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11381
11382        synchronized (mPackages) {
11383            // We don't expect installation to fail beyond this point
11384
11385            // Add the new setting to mSettings
11386            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11387            // Add the new setting to mPackages
11388            mPackages.put(pkg.applicationInfo.packageName, pkg);
11389            // Make sure we don't accidentally delete its data.
11390            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11391            while (iter.hasNext()) {
11392                PackageCleanItem item = iter.next();
11393                if (pkgName.equals(item.packageName)) {
11394                    iter.remove();
11395                }
11396            }
11397
11398            // Add the package's KeySets to the global KeySetManagerService
11399            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11400            ksms.addScannedPackageLPw(pkg);
11401
11402            int N = pkg.providers.size();
11403            StringBuilder r = null;
11404            int i;
11405            for (i=0; i<N; i++) {
11406                PackageParser.Provider p = pkg.providers.get(i);
11407                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11408                        p.info.processName);
11409                mProviders.addProvider(p);
11410                p.syncable = p.info.isSyncable;
11411                if (p.info.authority != null) {
11412                    String names[] = p.info.authority.split(";");
11413                    p.info.authority = null;
11414                    for (int j = 0; j < names.length; j++) {
11415                        if (j == 1 && p.syncable) {
11416                            // We only want the first authority for a provider to possibly be
11417                            // syncable, so if we already added this provider using a different
11418                            // authority clear the syncable flag. We copy the provider before
11419                            // changing it because the mProviders object contains a reference
11420                            // to a provider that we don't want to change.
11421                            // Only do this for the second authority since the resulting provider
11422                            // object can be the same for all future authorities for this provider.
11423                            p = new PackageParser.Provider(p);
11424                            p.syncable = false;
11425                        }
11426                        if (!mProvidersByAuthority.containsKey(names[j])) {
11427                            mProvidersByAuthority.put(names[j], p);
11428                            if (p.info.authority == null) {
11429                                p.info.authority = names[j];
11430                            } else {
11431                                p.info.authority = p.info.authority + ";" + names[j];
11432                            }
11433                            if (DEBUG_PACKAGE_SCANNING) {
11434                                if (chatty)
11435                                    Log.d(TAG, "Registered content provider: " + names[j]
11436                                            + ", className = " + p.info.name + ", isSyncable = "
11437                                            + p.info.isSyncable);
11438                            }
11439                        } else {
11440                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11441                            Slog.w(TAG, "Skipping provider name " + names[j] +
11442                                    " (in package " + pkg.applicationInfo.packageName +
11443                                    "): name already used by "
11444                                    + ((other != null && other.getComponentName() != null)
11445                                            ? other.getComponentName().getPackageName() : "?"));
11446                        }
11447                    }
11448                }
11449                if (chatty) {
11450                    if (r == null) {
11451                        r = new StringBuilder(256);
11452                    } else {
11453                        r.append(' ');
11454                    }
11455                    r.append(p.info.name);
11456                }
11457            }
11458            if (r != null) {
11459                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11460            }
11461
11462            N = pkg.services.size();
11463            r = null;
11464            for (i=0; i<N; i++) {
11465                PackageParser.Service s = pkg.services.get(i);
11466                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11467                        s.info.processName);
11468                mServices.addService(s);
11469                if (chatty) {
11470                    if (r == null) {
11471                        r = new StringBuilder(256);
11472                    } else {
11473                        r.append(' ');
11474                    }
11475                    r.append(s.info.name);
11476                }
11477            }
11478            if (r != null) {
11479                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11480            }
11481
11482            N = pkg.receivers.size();
11483            r = null;
11484            for (i=0; i<N; i++) {
11485                PackageParser.Activity a = pkg.receivers.get(i);
11486                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11487                        a.info.processName);
11488                mReceivers.addActivity(a, "receiver");
11489                if (chatty) {
11490                    if (r == null) {
11491                        r = new StringBuilder(256);
11492                    } else {
11493                        r.append(' ');
11494                    }
11495                    r.append(a.info.name);
11496                }
11497            }
11498            if (r != null) {
11499                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11500            }
11501
11502            N = pkg.activities.size();
11503            r = null;
11504            for (i=0; i<N; i++) {
11505                PackageParser.Activity a = pkg.activities.get(i);
11506                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11507                        a.info.processName);
11508                mActivities.addActivity(a, "activity");
11509                if (chatty) {
11510                    if (r == null) {
11511                        r = new StringBuilder(256);
11512                    } else {
11513                        r.append(' ');
11514                    }
11515                    r.append(a.info.name);
11516                }
11517            }
11518            if (r != null) {
11519                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11520            }
11521
11522            // Don't allow ephemeral applications to define new permissions groups.
11523            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11524                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11525                        + " ignored: instant apps cannot define new permission groups.");
11526            } else {
11527                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11528            }
11529
11530            // Don't allow ephemeral applications to define new permissions.
11531            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11532                Slog.w(TAG, "Permissions from package " + pkg.packageName
11533                        + " ignored: instant apps cannot define new permissions.");
11534            } else {
11535                mPermissionManager.addAllPermissions(pkg, chatty);
11536            }
11537
11538            N = pkg.instrumentation.size();
11539            r = null;
11540            for (i=0; i<N; i++) {
11541                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11542                a.info.packageName = pkg.applicationInfo.packageName;
11543                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11544                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11545                a.info.splitNames = pkg.splitNames;
11546                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11547                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11548                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11549                a.info.dataDir = pkg.applicationInfo.dataDir;
11550                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11551                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11552                a.info.primaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11553                a.info.secondaryCpuAbi = pkg.applicationInfo.secondaryCpuAbi;
11554                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11555                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11556                mInstrumentation.put(a.getComponentName(), a);
11557                if (chatty) {
11558                    if (r == null) {
11559                        r = new StringBuilder(256);
11560                    } else {
11561                        r.append(' ');
11562                    }
11563                    r.append(a.info.name);
11564                }
11565            }
11566            if (r != null) {
11567                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11568            }
11569
11570            if (pkg.protectedBroadcasts != null) {
11571                N = pkg.protectedBroadcasts.size();
11572                synchronized (mProtectedBroadcasts) {
11573                    for (i = 0; i < N; i++) {
11574                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11575                    }
11576                }
11577            }
11578
11579            if (oldPkg != null) {
11580                // We need to call revokeRuntimePermissionsIfGroupChanged async as permission
11581                // revoke callbacks from this method might need to kill apps which need the
11582                // mPackages lock on a different thread. This would dead lock.
11583                //
11584                // Hence create a copy of all package names and pass it into
11585                // revokeRuntimePermissionsIfGroupChanged. Only for those permissions might get
11586                // revoked. If a new package is added before the async code runs the permission
11587                // won't be granted yet, hence new packages are no problem.
11588                final ArrayList<String> allPackageNames = new ArrayList<>(mPackages.keySet());
11589
11590                AsyncTask.execute(() ->
11591                        mPermissionManager.revokeRuntimePermissionsIfGroupChanged(pkg, oldPkg,
11592                                allPackageNames, mPermissionCallback));
11593            }
11594        }
11595
11596        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11597    }
11598
11599    /**
11600     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11601     * is derived purely on the basis of the contents of {@code scanFile} and
11602     * {@code cpuAbiOverride}.
11603     *
11604     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11605     */
11606    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11607            boolean extractLibs)
11608                    throws PackageManagerException {
11609        // Give ourselves some initial paths; we'll come back for another
11610        // pass once we've determined ABI below.
11611        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11612
11613        // We would never need to extract libs for forward-locked and external packages,
11614        // since the container service will do it for us. We shouldn't attempt to
11615        // extract libs from system app when it was not updated.
11616        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11617                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11618            extractLibs = false;
11619        }
11620
11621        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11622        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11623
11624        NativeLibraryHelper.Handle handle = null;
11625        try {
11626            handle = NativeLibraryHelper.Handle.create(pkg);
11627            // TODO(multiArch): This can be null for apps that didn't go through the
11628            // usual installation process. We can calculate it again, like we
11629            // do during install time.
11630            //
11631            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11632            // unnecessary.
11633            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11634
11635            // Null out the abis so that they can be recalculated.
11636            pkg.applicationInfo.primaryCpuAbi = null;
11637            pkg.applicationInfo.secondaryCpuAbi = null;
11638            if (isMultiArch(pkg.applicationInfo)) {
11639                // Warn if we've set an abiOverride for multi-lib packages..
11640                // By definition, we need to copy both 32 and 64 bit libraries for
11641                // such packages.
11642                if (pkg.cpuAbiOverride != null
11643                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11644                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11645                }
11646
11647                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11648                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11649                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11650                    if (extractLibs) {
11651                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11652                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11653                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11654                                useIsaSpecificSubdirs);
11655                    } else {
11656                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11657                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11658                    }
11659                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11660                }
11661
11662                // Shared library native code should be in the APK zip aligned
11663                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11664                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11665                            "Shared library native lib extraction not supported");
11666                }
11667
11668                maybeThrowExceptionForMultiArchCopy(
11669                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11670
11671                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11672                    if (extractLibs) {
11673                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11674                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11675                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11676                                useIsaSpecificSubdirs);
11677                    } else {
11678                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11679                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11680                    }
11681                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11682                }
11683
11684                maybeThrowExceptionForMultiArchCopy(
11685                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11686
11687                if (abi64 >= 0) {
11688                    // Shared library native libs should be in the APK zip aligned
11689                    if (extractLibs && pkg.isLibrary()) {
11690                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11691                                "Shared library native lib extraction not supported");
11692                    }
11693                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11694                }
11695
11696                if (abi32 >= 0) {
11697                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11698                    if (abi64 >= 0) {
11699                        if (pkg.use32bitAbi) {
11700                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11701                            pkg.applicationInfo.primaryCpuAbi = abi;
11702                        } else {
11703                            pkg.applicationInfo.secondaryCpuAbi = abi;
11704                        }
11705                    } else {
11706                        pkg.applicationInfo.primaryCpuAbi = abi;
11707                    }
11708                }
11709            } else {
11710                String[] abiList = (cpuAbiOverride != null) ?
11711                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11712
11713                // Enable gross and lame hacks for apps that are built with old
11714                // SDK tools. We must scan their APKs for renderscript bitcode and
11715                // not launch them if it's present. Don't bother checking on devices
11716                // that don't have 64 bit support.
11717                boolean needsRenderScriptOverride = false;
11718                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11719                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11720                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11721                    needsRenderScriptOverride = true;
11722                }
11723
11724                final int copyRet;
11725                if (extractLibs) {
11726                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11727                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11728                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11729                } else {
11730                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11731                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11732                }
11733                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11734
11735                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11736                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11737                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11738                }
11739
11740                if (copyRet >= 0) {
11741                    // Shared libraries that have native libs must be multi-architecture
11742                    if (pkg.isLibrary()) {
11743                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11744                                "Shared library with native libs must be multiarch");
11745                    }
11746                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11747                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11748                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11749                } else if (needsRenderScriptOverride) {
11750                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11751                }
11752            }
11753        } catch (IOException ioe) {
11754            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11755        } finally {
11756            IoUtils.closeQuietly(handle);
11757        }
11758
11759        // Now that we've calculated the ABIs and determined if it's an internal app,
11760        // we will go ahead and populate the nativeLibraryPath.
11761        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11762    }
11763
11764    /**
11765     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11766     * i.e, so that all packages can be run inside a single process if required.
11767     *
11768     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11769     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11770     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11771     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11772     * updating a package that belongs to a shared user.
11773     *
11774     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11775     * adds unnecessary complexity.
11776     */
11777    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11778            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11779        List<String> changedAbiCodePath = null;
11780        String requiredInstructionSet = null;
11781        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11782            requiredInstructionSet = VMRuntime.getInstructionSet(
11783                     scannedPackage.applicationInfo.primaryCpuAbi);
11784        }
11785
11786        PackageSetting requirer = null;
11787        for (PackageSetting ps : packagesForUser) {
11788            // If packagesForUser contains scannedPackage, we skip it. This will happen
11789            // when scannedPackage is an update of an existing package. Without this check,
11790            // we will never be able to change the ABI of any package belonging to a shared
11791            // user, even if it's compatible with other packages.
11792            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11793                if (ps.primaryCpuAbiString == null) {
11794                    continue;
11795                }
11796
11797                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11798                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11799                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11800                    // this but there's not much we can do.
11801                    String errorMessage = "Instruction set mismatch, "
11802                            + ((requirer == null) ? "[caller]" : requirer)
11803                            + " requires " + requiredInstructionSet + " whereas " + ps
11804                            + " requires " + instructionSet;
11805                    Slog.w(TAG, errorMessage);
11806                }
11807
11808                if (requiredInstructionSet == null) {
11809                    requiredInstructionSet = instructionSet;
11810                    requirer = ps;
11811                }
11812            }
11813        }
11814
11815        if (requiredInstructionSet != null) {
11816            String adjustedAbi;
11817            if (requirer != null) {
11818                // requirer != null implies that either scannedPackage was null or that scannedPackage
11819                // did not require an ABI, in which case we have to adjust scannedPackage to match
11820                // the ABI of the set (which is the same as requirer's ABI)
11821                adjustedAbi = requirer.primaryCpuAbiString;
11822                if (scannedPackage != null) {
11823                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11824                }
11825            } else {
11826                // requirer == null implies that we're updating all ABIs in the set to
11827                // match scannedPackage.
11828                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11829            }
11830
11831            for (PackageSetting ps : packagesForUser) {
11832                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11833                    if (ps.primaryCpuAbiString != null) {
11834                        continue;
11835                    }
11836
11837                    ps.primaryCpuAbiString = adjustedAbi;
11838                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11839                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11840                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11841                        if (DEBUG_ABI_SELECTION) {
11842                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11843                                    + " (requirer="
11844                                    + (requirer != null ? requirer.pkg : "null")
11845                                    + ", scannedPackage="
11846                                    + (scannedPackage != null ? scannedPackage : "null")
11847                                    + ")");
11848                        }
11849                        if (changedAbiCodePath == null) {
11850                            changedAbiCodePath = new ArrayList<>();
11851                        }
11852                        changedAbiCodePath.add(ps.codePathString);
11853                    }
11854                }
11855            }
11856        }
11857        return changedAbiCodePath;
11858    }
11859
11860    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11861        synchronized (mPackages) {
11862            mResolverReplaced = true;
11863            // Set up information for custom user intent resolution activity.
11864            mResolveActivity.applicationInfo = pkg.applicationInfo;
11865            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11866            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11867            mResolveActivity.processName = pkg.applicationInfo.packageName;
11868            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11869            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11870                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11871            mResolveActivity.theme = 0;
11872            mResolveActivity.exported = true;
11873            mResolveActivity.enabled = true;
11874            mResolveInfo.activityInfo = mResolveActivity;
11875            mResolveInfo.priority = 0;
11876            mResolveInfo.preferredOrder = 0;
11877            mResolveInfo.match = 0;
11878            mResolveComponentName = mCustomResolverComponentName;
11879            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11880                    mResolveComponentName);
11881        }
11882    }
11883
11884    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11885        if (installerActivity == null) {
11886            if (DEBUG_INSTANT) {
11887                Slog.d(TAG, "Clear ephemeral installer activity");
11888            }
11889            mInstantAppInstallerActivity = null;
11890            return;
11891        }
11892
11893        if (DEBUG_INSTANT) {
11894            Slog.d(TAG, "Set ephemeral installer activity: "
11895                    + installerActivity.getComponentName());
11896        }
11897        // Set up information for ephemeral installer activity
11898        mInstantAppInstallerActivity = installerActivity;
11899        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11900                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11901        mInstantAppInstallerActivity.exported = true;
11902        mInstantAppInstallerActivity.enabled = true;
11903        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11904        mInstantAppInstallerInfo.priority = 1;
11905        mInstantAppInstallerInfo.preferredOrder = 1;
11906        mInstantAppInstallerInfo.isDefault = true;
11907        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11908                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11909    }
11910
11911    private static String calculateBundledApkRoot(final String codePathString) {
11912        final File codePath = new File(codePathString);
11913        final File codeRoot;
11914        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11915            codeRoot = Environment.getRootDirectory();
11916        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11917            codeRoot = Environment.getOemDirectory();
11918        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11919            codeRoot = Environment.getVendorDirectory();
11920        } else if (FileUtils.contains(Environment.getOdmDirectory(), codePath)) {
11921            codeRoot = Environment.getOdmDirectory();
11922        } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) {
11923            codeRoot = Environment.getProductDirectory();
11924        } else {
11925            // Unrecognized code path; take its top real segment as the apk root:
11926            // e.g. /something/app/blah.apk => /something
11927            try {
11928                File f = codePath.getCanonicalFile();
11929                File parent = f.getParentFile();    // non-null because codePath is a file
11930                File tmp;
11931                while ((tmp = parent.getParentFile()) != null) {
11932                    f = parent;
11933                    parent = tmp;
11934                }
11935                codeRoot = f;
11936                Slog.w(TAG, "Unrecognized code path "
11937                        + codePath + " - using " + codeRoot);
11938            } catch (IOException e) {
11939                // Can't canonicalize the code path -- shenanigans?
11940                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11941                return Environment.getRootDirectory().getPath();
11942            }
11943        }
11944        return codeRoot.getPath();
11945    }
11946
11947    /**
11948     * Derive and set the location of native libraries for the given package,
11949     * which varies depending on where and how the package was installed.
11950     */
11951    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11952        final ApplicationInfo info = pkg.applicationInfo;
11953        final String codePath = pkg.codePath;
11954        final File codeFile = new File(codePath);
11955        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11956        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11957
11958        info.nativeLibraryRootDir = null;
11959        info.nativeLibraryRootRequiresIsa = false;
11960        info.nativeLibraryDir = null;
11961        info.secondaryNativeLibraryDir = null;
11962
11963        if (isApkFile(codeFile)) {
11964            // Monolithic install
11965            if (bundledApp) {
11966                // If "/system/lib64/apkname" exists, assume that is the per-package
11967                // native library directory to use; otherwise use "/system/lib/apkname".
11968                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11969                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11970                        getPrimaryInstructionSet(info));
11971
11972                // This is a bundled system app so choose the path based on the ABI.
11973                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11974                // is just the default path.
11975                final String apkName = deriveCodePathName(codePath);
11976                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11977                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11978                        apkName).getAbsolutePath();
11979
11980                if (info.secondaryCpuAbi != null) {
11981                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11982                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11983                            secondaryLibDir, apkName).getAbsolutePath();
11984                }
11985            } else if (asecApp) {
11986                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11987                        .getAbsolutePath();
11988            } else {
11989                final String apkName = deriveCodePathName(codePath);
11990                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11991                        .getAbsolutePath();
11992            }
11993
11994            info.nativeLibraryRootRequiresIsa = false;
11995            info.nativeLibraryDir = info.nativeLibraryRootDir;
11996        } else {
11997            // Cluster install
11998            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11999            info.nativeLibraryRootRequiresIsa = true;
12000
12001            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
12002                    getPrimaryInstructionSet(info)).getAbsolutePath();
12003
12004            if (info.secondaryCpuAbi != null) {
12005                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
12006                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
12007            }
12008        }
12009    }
12010
12011    /**
12012     * Calculate the abis and roots for a bundled app. These can uniquely
12013     * be determined from the contents of the system partition, i.e whether
12014     * it contains 64 or 32 bit shared libraries etc. We do not validate any
12015     * of this information, and instead assume that the system was built
12016     * sensibly.
12017     */
12018    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
12019                                           PackageSetting pkgSetting) {
12020        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
12021
12022        // If "/system/lib64/apkname" exists, assume that is the per-package
12023        // native library directory to use; otherwise use "/system/lib/apkname".
12024        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
12025        setBundledAppAbi(pkg, apkRoot, apkName);
12026        // pkgSetting might be null during rescan following uninstall of updates
12027        // to a bundled app, so accommodate that possibility.  The settings in
12028        // that case will be established later from the parsed package.
12029        //
12030        // If the settings aren't null, sync them up with what we've just derived.
12031        // note that apkRoot isn't stored in the package settings.
12032        if (pkgSetting != null) {
12033            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
12034            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
12035        }
12036    }
12037
12038    /**
12039     * Deduces the ABI of a bundled app and sets the relevant fields on the
12040     * parsed pkg object.
12041     *
12042     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12043     *        under which system libraries are installed.
12044     * @param apkName the name of the installed package.
12045     */
12046    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12047        final File codeFile = new File(pkg.codePath);
12048
12049        final boolean has64BitLibs;
12050        final boolean has32BitLibs;
12051        if (isApkFile(codeFile)) {
12052            // Monolithic install
12053            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12054            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12055        } else {
12056            // Cluster install
12057            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12058            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12059                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12060                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12061                has64BitLibs = (new File(rootDir, isa)).exists();
12062            } else {
12063                has64BitLibs = false;
12064            }
12065            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12066                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12067                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12068                has32BitLibs = (new File(rootDir, isa)).exists();
12069            } else {
12070                has32BitLibs = false;
12071            }
12072        }
12073
12074        if (has64BitLibs && !has32BitLibs) {
12075            // The package has 64 bit libs, but not 32 bit libs. Its primary
12076            // ABI should be 64 bit. We can safely assume here that the bundled
12077            // native libraries correspond to the most preferred ABI in the list.
12078
12079            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12080            pkg.applicationInfo.secondaryCpuAbi = null;
12081        } else if (has32BitLibs && !has64BitLibs) {
12082            // The package has 32 bit libs but not 64 bit libs. Its primary
12083            // ABI should be 32 bit.
12084
12085            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12086            pkg.applicationInfo.secondaryCpuAbi = null;
12087        } else if (has32BitLibs && has64BitLibs) {
12088            // The application has both 64 and 32 bit bundled libraries. We check
12089            // here that the app declares multiArch support, and warn if it doesn't.
12090            //
12091            // We will be lenient here and record both ABIs. The primary will be the
12092            // ABI that's higher on the list, i.e, a device that's configured to prefer
12093            // 64 bit apps will see a 64 bit primary ABI,
12094
12095            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12096                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12097            }
12098
12099            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12100                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12101                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12102            } else {
12103                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12104                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12105            }
12106        } else {
12107            pkg.applicationInfo.primaryCpuAbi = null;
12108            pkg.applicationInfo.secondaryCpuAbi = null;
12109        }
12110    }
12111
12112    private void killApplication(String pkgName, int appId, String reason) {
12113        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12114    }
12115
12116    private void killApplication(String pkgName, int appId, int userId, String reason) {
12117        // Request the ActivityManager to kill the process(only for existing packages)
12118        // so that we do not end up in a confused state while the user is still using the older
12119        // version of the application while the new one gets installed.
12120        final long token = Binder.clearCallingIdentity();
12121        try {
12122            IActivityManager am = ActivityManager.getService();
12123            if (am != null) {
12124                try {
12125                    am.killApplication(pkgName, appId, userId, reason);
12126                } catch (RemoteException e) {
12127                }
12128            }
12129        } finally {
12130            Binder.restoreCallingIdentity(token);
12131        }
12132    }
12133
12134    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12135        // Remove the parent package setting
12136        PackageSetting ps = (PackageSetting) pkg.mExtras;
12137        if (ps != null) {
12138            removePackageLI(ps, chatty);
12139        }
12140        // Remove the child package setting
12141        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12142        for (int i = 0; i < childCount; i++) {
12143            PackageParser.Package childPkg = pkg.childPackages.get(i);
12144            ps = (PackageSetting) childPkg.mExtras;
12145            if (ps != null) {
12146                removePackageLI(ps, chatty);
12147            }
12148        }
12149    }
12150
12151    void removePackageLI(PackageSetting ps, boolean chatty) {
12152        if (DEBUG_INSTALL) {
12153            if (chatty)
12154                Log.d(TAG, "Removing package " + ps.name);
12155        }
12156
12157        // writer
12158        synchronized (mPackages) {
12159            mPackages.remove(ps.name);
12160            final PackageParser.Package pkg = ps.pkg;
12161            if (pkg != null) {
12162                cleanPackageDataStructuresLILPw(pkg, chatty);
12163            }
12164        }
12165    }
12166
12167    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12168        if (DEBUG_INSTALL) {
12169            if (chatty)
12170                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12171        }
12172
12173        // writer
12174        synchronized (mPackages) {
12175            // Remove the parent package
12176            mPackages.remove(pkg.applicationInfo.packageName);
12177            cleanPackageDataStructuresLILPw(pkg, chatty);
12178
12179            // Remove the child packages
12180            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12181            for (int i = 0; i < childCount; i++) {
12182                PackageParser.Package childPkg = pkg.childPackages.get(i);
12183                mPackages.remove(childPkg.applicationInfo.packageName);
12184                cleanPackageDataStructuresLILPw(childPkg, chatty);
12185            }
12186        }
12187    }
12188
12189    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12190        int N = pkg.providers.size();
12191        StringBuilder r = null;
12192        int i;
12193        for (i=0; i<N; i++) {
12194            PackageParser.Provider p = pkg.providers.get(i);
12195            mProviders.removeProvider(p);
12196            if (p.info.authority == null) {
12197
12198                /* There was another ContentProvider with this authority when
12199                 * this app was installed so this authority is null,
12200                 * Ignore it as we don't have to unregister the provider.
12201                 */
12202                continue;
12203            }
12204            String names[] = p.info.authority.split(";");
12205            for (int j = 0; j < names.length; j++) {
12206                if (mProvidersByAuthority.get(names[j]) == p) {
12207                    mProvidersByAuthority.remove(names[j]);
12208                    if (DEBUG_REMOVE) {
12209                        if (chatty)
12210                            Log.d(TAG, "Unregistered content provider: " + names[j]
12211                                    + ", className = " + p.info.name + ", isSyncable = "
12212                                    + p.info.isSyncable);
12213                    }
12214                }
12215            }
12216            if (DEBUG_REMOVE && chatty) {
12217                if (r == null) {
12218                    r = new StringBuilder(256);
12219                } else {
12220                    r.append(' ');
12221                }
12222                r.append(p.info.name);
12223            }
12224        }
12225        if (r != null) {
12226            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12227        }
12228
12229        N = pkg.services.size();
12230        r = null;
12231        for (i=0; i<N; i++) {
12232            PackageParser.Service s = pkg.services.get(i);
12233            mServices.removeService(s);
12234            if (chatty) {
12235                if (r == null) {
12236                    r = new StringBuilder(256);
12237                } else {
12238                    r.append(' ');
12239                }
12240                r.append(s.info.name);
12241            }
12242        }
12243        if (r != null) {
12244            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12245        }
12246
12247        N = pkg.receivers.size();
12248        r = null;
12249        for (i=0; i<N; i++) {
12250            PackageParser.Activity a = pkg.receivers.get(i);
12251            mReceivers.removeActivity(a, "receiver");
12252            if (DEBUG_REMOVE && chatty) {
12253                if (r == null) {
12254                    r = new StringBuilder(256);
12255                } else {
12256                    r.append(' ');
12257                }
12258                r.append(a.info.name);
12259            }
12260        }
12261        if (r != null) {
12262            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12263        }
12264
12265        N = pkg.activities.size();
12266        r = null;
12267        for (i=0; i<N; i++) {
12268            PackageParser.Activity a = pkg.activities.get(i);
12269            mActivities.removeActivity(a, "activity");
12270            if (DEBUG_REMOVE && chatty) {
12271                if (r == null) {
12272                    r = new StringBuilder(256);
12273                } else {
12274                    r.append(' ');
12275                }
12276                r.append(a.info.name);
12277            }
12278        }
12279        if (r != null) {
12280            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12281        }
12282
12283        mPermissionManager.removeAllPermissions(pkg, chatty);
12284
12285        N = pkg.instrumentation.size();
12286        r = null;
12287        for (i=0; i<N; i++) {
12288            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12289            mInstrumentation.remove(a.getComponentName());
12290            if (DEBUG_REMOVE && chatty) {
12291                if (r == null) {
12292                    r = new StringBuilder(256);
12293                } else {
12294                    r.append(' ');
12295                }
12296                r.append(a.info.name);
12297            }
12298        }
12299        if (r != null) {
12300            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12301        }
12302
12303        r = null;
12304        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12305            // Only system apps can hold shared libraries.
12306            if (pkg.libraryNames != null) {
12307                for (i = 0; i < pkg.libraryNames.size(); i++) {
12308                    String name = pkg.libraryNames.get(i);
12309                    if (removeSharedLibraryLPw(name, 0)) {
12310                        if (DEBUG_REMOVE && chatty) {
12311                            if (r == null) {
12312                                r = new StringBuilder(256);
12313                            } else {
12314                                r.append(' ');
12315                            }
12316                            r.append(name);
12317                        }
12318                    }
12319                }
12320            }
12321        }
12322
12323        r = null;
12324
12325        // Any package can hold static shared libraries.
12326        if (pkg.staticSharedLibName != null) {
12327            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12328                if (DEBUG_REMOVE && chatty) {
12329                    if (r == null) {
12330                        r = new StringBuilder(256);
12331                    } else {
12332                        r.append(' ');
12333                    }
12334                    r.append(pkg.staticSharedLibName);
12335                }
12336            }
12337        }
12338
12339        if (r != null) {
12340            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12341        }
12342    }
12343
12344
12345    final class ActivityIntentResolver
12346            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12347        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12348                boolean defaultOnly, int userId) {
12349            if (!sUserManager.exists(userId)) return null;
12350            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12351            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12352        }
12353
12354        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12355                int userId) {
12356            if (!sUserManager.exists(userId)) return null;
12357            mFlags = flags;
12358            return super.queryIntent(intent, resolvedType,
12359                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12360                    userId);
12361        }
12362
12363        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12364                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12365            if (!sUserManager.exists(userId)) return null;
12366            if (packageActivities == null) {
12367                return null;
12368            }
12369            mFlags = flags;
12370            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12371            final int N = packageActivities.size();
12372            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12373                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12374
12375            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12376            for (int i = 0; i < N; ++i) {
12377                intentFilters = packageActivities.get(i).intents;
12378                if (intentFilters != null && intentFilters.size() > 0) {
12379                    PackageParser.ActivityIntentInfo[] array =
12380                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12381                    intentFilters.toArray(array);
12382                    listCut.add(array);
12383                }
12384            }
12385            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12386        }
12387
12388        /**
12389         * Finds a privileged activity that matches the specified activity names.
12390         */
12391        private PackageParser.Activity findMatchingActivity(
12392                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12393            for (PackageParser.Activity sysActivity : activityList) {
12394                if (sysActivity.info.name.equals(activityInfo.name)) {
12395                    return sysActivity;
12396                }
12397                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12398                    return sysActivity;
12399                }
12400                if (sysActivity.info.targetActivity != null) {
12401                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12402                        return sysActivity;
12403                    }
12404                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12405                        return sysActivity;
12406                    }
12407                }
12408            }
12409            return null;
12410        }
12411
12412        public class IterGenerator<E> {
12413            public Iterator<E> generate(ActivityIntentInfo info) {
12414                return null;
12415            }
12416        }
12417
12418        public class ActionIterGenerator extends IterGenerator<String> {
12419            @Override
12420            public Iterator<String> generate(ActivityIntentInfo info) {
12421                return info.actionsIterator();
12422            }
12423        }
12424
12425        public class CategoriesIterGenerator extends IterGenerator<String> {
12426            @Override
12427            public Iterator<String> generate(ActivityIntentInfo info) {
12428                return info.categoriesIterator();
12429            }
12430        }
12431
12432        public class SchemesIterGenerator extends IterGenerator<String> {
12433            @Override
12434            public Iterator<String> generate(ActivityIntentInfo info) {
12435                return info.schemesIterator();
12436            }
12437        }
12438
12439        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12440            @Override
12441            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12442                return info.authoritiesIterator();
12443            }
12444        }
12445
12446        /**
12447         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12448         * MODIFIED. Do not pass in a list that should not be changed.
12449         */
12450        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12451                IterGenerator<T> generator, Iterator<T> searchIterator) {
12452            // loop through the set of actions; every one must be found in the intent filter
12453            while (searchIterator.hasNext()) {
12454                // we must have at least one filter in the list to consider a match
12455                if (intentList.size() == 0) {
12456                    break;
12457                }
12458
12459                final T searchAction = searchIterator.next();
12460
12461                // loop through the set of intent filters
12462                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12463                while (intentIter.hasNext()) {
12464                    final ActivityIntentInfo intentInfo = intentIter.next();
12465                    boolean selectionFound = false;
12466
12467                    // loop through the intent filter's selection criteria; at least one
12468                    // of them must match the searched criteria
12469                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12470                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12471                        final T intentSelection = intentSelectionIter.next();
12472                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12473                            selectionFound = true;
12474                            break;
12475                        }
12476                    }
12477
12478                    // the selection criteria wasn't found in this filter's set; this filter
12479                    // is not a potential match
12480                    if (!selectionFound) {
12481                        intentIter.remove();
12482                    }
12483                }
12484            }
12485        }
12486
12487        private boolean isProtectedAction(ActivityIntentInfo filter) {
12488            final Iterator<String> actionsIter = filter.actionsIterator();
12489            while (actionsIter != null && actionsIter.hasNext()) {
12490                final String filterAction = actionsIter.next();
12491                if (PROTECTED_ACTIONS.contains(filterAction)) {
12492                    return true;
12493                }
12494            }
12495            return false;
12496        }
12497
12498        /**
12499         * Adjusts the priority of the given intent filter according to policy.
12500         * <p>
12501         * <ul>
12502         * <li>The priority for non privileged applications is capped to '0'</li>
12503         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12504         * <li>The priority for unbundled updates to privileged applications is capped to the
12505         *      priority defined on the system partition</li>
12506         * </ul>
12507         * <p>
12508         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12509         * allowed to obtain any priority on any action.
12510         */
12511        private void adjustPriority(
12512                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12513            // nothing to do; priority is fine as-is
12514            if (intent.getPriority() <= 0) {
12515                return;
12516            }
12517
12518            final ActivityInfo activityInfo = intent.activity.info;
12519            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12520
12521            final boolean privilegedApp =
12522                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12523            if (!privilegedApp) {
12524                // non-privileged applications can never define a priority >0
12525                if (DEBUG_FILTERS) {
12526                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12527                            + " package: " + applicationInfo.packageName
12528                            + " activity: " + intent.activity.className
12529                            + " origPrio: " + intent.getPriority());
12530                }
12531                intent.setPriority(0);
12532                return;
12533            }
12534
12535            if (systemActivities == null) {
12536                // the system package is not disabled; we're parsing the system partition
12537                if (isProtectedAction(intent)) {
12538                    if (mDeferProtectedFilters) {
12539                        // We can't deal with these just yet. No component should ever obtain a
12540                        // >0 priority for a protected actions, with ONE exception -- the setup
12541                        // wizard. The setup wizard, however, cannot be known until we're able to
12542                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12543                        // until all intent filters have been processed. Chicken, meet egg.
12544                        // Let the filter temporarily have a high priority and rectify the
12545                        // priorities after all system packages have been scanned.
12546                        mProtectedFilters.add(intent);
12547                        if (DEBUG_FILTERS) {
12548                            Slog.i(TAG, "Protected action; save for later;"
12549                                    + " package: " + applicationInfo.packageName
12550                                    + " activity: " + intent.activity.className
12551                                    + " origPrio: " + intent.getPriority());
12552                        }
12553                        return;
12554                    } else {
12555                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12556                            Slog.i(TAG, "No setup wizard;"
12557                                + " All protected intents capped to priority 0");
12558                        }
12559                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12560                            if (DEBUG_FILTERS) {
12561                                Slog.i(TAG, "Found setup wizard;"
12562                                    + " allow priority " + intent.getPriority() + ";"
12563                                    + " package: " + intent.activity.info.packageName
12564                                    + " activity: " + intent.activity.className
12565                                    + " priority: " + intent.getPriority());
12566                            }
12567                            // setup wizard gets whatever it wants
12568                            return;
12569                        }
12570                        if (DEBUG_FILTERS) {
12571                            Slog.i(TAG, "Protected action; cap priority to 0;"
12572                                    + " package: " + intent.activity.info.packageName
12573                                    + " activity: " + intent.activity.className
12574                                    + " origPrio: " + intent.getPriority());
12575                        }
12576                        intent.setPriority(0);
12577                        return;
12578                    }
12579                }
12580                // privileged apps on the system image get whatever priority they request
12581                return;
12582            }
12583
12584            // privileged app unbundled update ... try to find the same activity
12585            final PackageParser.Activity foundActivity =
12586                    findMatchingActivity(systemActivities, activityInfo);
12587            if (foundActivity == null) {
12588                // this is a new activity; it cannot obtain >0 priority
12589                if (DEBUG_FILTERS) {
12590                    Slog.i(TAG, "New activity; cap priority to 0;"
12591                            + " package: " + applicationInfo.packageName
12592                            + " activity: " + intent.activity.className
12593                            + " origPrio: " + intent.getPriority());
12594                }
12595                intent.setPriority(0);
12596                return;
12597            }
12598
12599            // found activity, now check for filter equivalence
12600
12601            // a shallow copy is enough; we modify the list, not its contents
12602            final List<ActivityIntentInfo> intentListCopy =
12603                    new ArrayList<>(foundActivity.intents);
12604            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12605
12606            // find matching action subsets
12607            final Iterator<String> actionsIterator = intent.actionsIterator();
12608            if (actionsIterator != null) {
12609                getIntentListSubset(
12610                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12611                if (intentListCopy.size() == 0) {
12612                    // no more intents to match; we're not equivalent
12613                    if (DEBUG_FILTERS) {
12614                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12615                                + " package: " + applicationInfo.packageName
12616                                + " activity: " + intent.activity.className
12617                                + " origPrio: " + intent.getPriority());
12618                    }
12619                    intent.setPriority(0);
12620                    return;
12621                }
12622            }
12623
12624            // find matching category subsets
12625            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12626            if (categoriesIterator != null) {
12627                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12628                        categoriesIterator);
12629                if (intentListCopy.size() == 0) {
12630                    // no more intents to match; we're not equivalent
12631                    if (DEBUG_FILTERS) {
12632                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12633                                + " package: " + applicationInfo.packageName
12634                                + " activity: " + intent.activity.className
12635                                + " origPrio: " + intent.getPriority());
12636                    }
12637                    intent.setPriority(0);
12638                    return;
12639                }
12640            }
12641
12642            // find matching schemes subsets
12643            final Iterator<String> schemesIterator = intent.schemesIterator();
12644            if (schemesIterator != null) {
12645                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12646                        schemesIterator);
12647                if (intentListCopy.size() == 0) {
12648                    // no more intents to match; we're not equivalent
12649                    if (DEBUG_FILTERS) {
12650                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12651                                + " package: " + applicationInfo.packageName
12652                                + " activity: " + intent.activity.className
12653                                + " origPrio: " + intent.getPriority());
12654                    }
12655                    intent.setPriority(0);
12656                    return;
12657                }
12658            }
12659
12660            // find matching authorities subsets
12661            final Iterator<IntentFilter.AuthorityEntry>
12662                    authoritiesIterator = intent.authoritiesIterator();
12663            if (authoritiesIterator != null) {
12664                getIntentListSubset(intentListCopy,
12665                        new AuthoritiesIterGenerator(),
12666                        authoritiesIterator);
12667                if (intentListCopy.size() == 0) {
12668                    // no more intents to match; we're not equivalent
12669                    if (DEBUG_FILTERS) {
12670                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12671                                + " package: " + applicationInfo.packageName
12672                                + " activity: " + intent.activity.className
12673                                + " origPrio: " + intent.getPriority());
12674                    }
12675                    intent.setPriority(0);
12676                    return;
12677                }
12678            }
12679
12680            // we found matching filter(s); app gets the max priority of all intents
12681            int cappedPriority = 0;
12682            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12683                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12684            }
12685            if (intent.getPriority() > cappedPriority) {
12686                if (DEBUG_FILTERS) {
12687                    Slog.i(TAG, "Found matching filter(s);"
12688                            + " cap priority to " + cappedPriority + ";"
12689                            + " package: " + applicationInfo.packageName
12690                            + " activity: " + intent.activity.className
12691                            + " origPrio: " + intent.getPriority());
12692                }
12693                intent.setPriority(cappedPriority);
12694                return;
12695            }
12696            // all this for nothing; the requested priority was <= what was on the system
12697        }
12698
12699        public final void addActivity(PackageParser.Activity a, String type) {
12700            mActivities.put(a.getComponentName(), a);
12701            if (DEBUG_SHOW_INFO)
12702                Log.v(
12703                TAG, "  " + type + " " +
12704                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12705            if (DEBUG_SHOW_INFO)
12706                Log.v(TAG, "    Class=" + a.info.name);
12707            final int NI = a.intents.size();
12708            for (int j=0; j<NI; j++) {
12709                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12710                if ("activity".equals(type)) {
12711                    final PackageSetting ps =
12712                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12713                    final List<PackageParser.Activity> systemActivities =
12714                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12715                    adjustPriority(systemActivities, intent);
12716                }
12717                if (DEBUG_SHOW_INFO) {
12718                    Log.v(TAG, "    IntentFilter:");
12719                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12720                }
12721                if (!intent.debugCheck()) {
12722                    Log.w(TAG, "==> For Activity " + a.info.name);
12723                }
12724                addFilter(intent);
12725            }
12726        }
12727
12728        public final void removeActivity(PackageParser.Activity a, String type) {
12729            mActivities.remove(a.getComponentName());
12730            if (DEBUG_SHOW_INFO) {
12731                Log.v(TAG, "  " + type + " "
12732                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12733                                : a.info.name) + ":");
12734                Log.v(TAG, "    Class=" + a.info.name);
12735            }
12736            final int NI = a.intents.size();
12737            for (int j=0; j<NI; j++) {
12738                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12739                if (DEBUG_SHOW_INFO) {
12740                    Log.v(TAG, "    IntentFilter:");
12741                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12742                }
12743                removeFilter(intent);
12744            }
12745        }
12746
12747        @Override
12748        protected boolean allowFilterResult(
12749                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12750            ActivityInfo filterAi = filter.activity.info;
12751            for (int i=dest.size()-1; i>=0; i--) {
12752                ActivityInfo destAi = dest.get(i).activityInfo;
12753                if (destAi.name == filterAi.name
12754                        && destAi.packageName == filterAi.packageName) {
12755                    return false;
12756                }
12757            }
12758            return true;
12759        }
12760
12761        @Override
12762        protected ActivityIntentInfo[] newArray(int size) {
12763            return new ActivityIntentInfo[size];
12764        }
12765
12766        @Override
12767        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12768            if (!sUserManager.exists(userId)) return true;
12769            PackageParser.Package p = filter.activity.owner;
12770            if (p != null) {
12771                PackageSetting ps = (PackageSetting)p.mExtras;
12772                if (ps != null) {
12773                    // System apps are never considered stopped for purposes of
12774                    // filtering, because there may be no way for the user to
12775                    // actually re-launch them.
12776                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12777                            && ps.getStopped(userId);
12778                }
12779            }
12780            return false;
12781        }
12782
12783        @Override
12784        protected boolean isPackageForFilter(String packageName,
12785                PackageParser.ActivityIntentInfo info) {
12786            return packageName.equals(info.activity.owner.packageName);
12787        }
12788
12789        @Override
12790        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12791                int match, int userId) {
12792            if (!sUserManager.exists(userId)) return null;
12793            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12794                return null;
12795            }
12796            final PackageParser.Activity activity = info.activity;
12797            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12798            if (ps == null) {
12799                return null;
12800            }
12801            final PackageUserState userState = ps.readUserState(userId);
12802            ActivityInfo ai =
12803                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12804            if (ai == null) {
12805                return null;
12806            }
12807            final boolean matchExplicitlyVisibleOnly =
12808                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12809            final boolean matchVisibleToInstantApp =
12810                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12811            final boolean componentVisible =
12812                    matchVisibleToInstantApp
12813                    && info.isVisibleToInstantApp()
12814                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12815            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12816            // throw out filters that aren't visible to ephemeral apps
12817            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12818                return null;
12819            }
12820            // throw out instant app filters if we're not explicitly requesting them
12821            if (!matchInstantApp && userState.instantApp) {
12822                return null;
12823            }
12824            // throw out instant app filters if updates are available; will trigger
12825            // instant app resolution
12826            if (userState.instantApp && ps.isUpdateAvailable()) {
12827                return null;
12828            }
12829            final ResolveInfo res = new ResolveInfo();
12830            res.activityInfo = ai;
12831            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12832                res.filter = info;
12833            }
12834            if (info != null) {
12835                res.handleAllWebDataURI = info.handleAllWebDataURI();
12836            }
12837            res.priority = info.getPriority();
12838            res.preferredOrder = activity.owner.mPreferredOrder;
12839            //System.out.println("Result: " + res.activityInfo.className +
12840            //                   " = " + res.priority);
12841            res.match = match;
12842            res.isDefault = info.hasDefault;
12843            res.labelRes = info.labelRes;
12844            res.nonLocalizedLabel = info.nonLocalizedLabel;
12845            if (userNeedsBadging(userId)) {
12846                res.noResourceId = true;
12847            } else {
12848                res.icon = info.icon;
12849            }
12850            res.iconResourceId = info.icon;
12851            res.system = res.activityInfo.applicationInfo.isSystemApp();
12852            res.isInstantAppAvailable = userState.instantApp;
12853            return res;
12854        }
12855
12856        @Override
12857        protected void sortResults(List<ResolveInfo> results) {
12858            Collections.sort(results, mResolvePrioritySorter);
12859        }
12860
12861        @Override
12862        protected void dumpFilter(PrintWriter out, String prefix,
12863                PackageParser.ActivityIntentInfo filter) {
12864            out.print(prefix); out.print(
12865                    Integer.toHexString(System.identityHashCode(filter.activity)));
12866                    out.print(' ');
12867                    filter.activity.printComponentShortName(out);
12868                    out.print(" filter ");
12869                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12870        }
12871
12872        @Override
12873        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12874            return filter.activity;
12875        }
12876
12877        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12878            PackageParser.Activity activity = (PackageParser.Activity)label;
12879            out.print(prefix); out.print(
12880                    Integer.toHexString(System.identityHashCode(activity)));
12881                    out.print(' ');
12882                    activity.printComponentShortName(out);
12883            if (count > 1) {
12884                out.print(" ("); out.print(count); out.print(" filters)");
12885            }
12886            out.println();
12887        }
12888
12889        // Keys are String (activity class name), values are Activity.
12890        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12891                = new ArrayMap<ComponentName, PackageParser.Activity>();
12892        private int mFlags;
12893    }
12894
12895    private final class ServiceIntentResolver
12896            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12897        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12898                boolean defaultOnly, int userId) {
12899            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12900            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12901        }
12902
12903        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12904                int userId) {
12905            if (!sUserManager.exists(userId)) return null;
12906            mFlags = flags;
12907            return super.queryIntent(intent, resolvedType,
12908                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12909                    userId);
12910        }
12911
12912        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12913                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12914            if (!sUserManager.exists(userId)) return null;
12915            if (packageServices == null) {
12916                return null;
12917            }
12918            mFlags = flags;
12919            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12920            final int N = packageServices.size();
12921            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12922                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12923
12924            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12925            for (int i = 0; i < N; ++i) {
12926                intentFilters = packageServices.get(i).intents;
12927                if (intentFilters != null && intentFilters.size() > 0) {
12928                    PackageParser.ServiceIntentInfo[] array =
12929                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12930                    intentFilters.toArray(array);
12931                    listCut.add(array);
12932                }
12933            }
12934            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12935        }
12936
12937        public final void addService(PackageParser.Service s) {
12938            mServices.put(s.getComponentName(), s);
12939            if (DEBUG_SHOW_INFO) {
12940                Log.v(TAG, "  "
12941                        + (s.info.nonLocalizedLabel != null
12942                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12943                Log.v(TAG, "    Class=" + s.info.name);
12944            }
12945            final int NI = s.intents.size();
12946            int j;
12947            for (j=0; j<NI; j++) {
12948                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12949                if (DEBUG_SHOW_INFO) {
12950                    Log.v(TAG, "    IntentFilter:");
12951                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12952                }
12953                if (!intent.debugCheck()) {
12954                    Log.w(TAG, "==> For Service " + s.info.name);
12955                }
12956                addFilter(intent);
12957            }
12958        }
12959
12960        public final void removeService(PackageParser.Service s) {
12961            mServices.remove(s.getComponentName());
12962            if (DEBUG_SHOW_INFO) {
12963                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12964                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12965                Log.v(TAG, "    Class=" + s.info.name);
12966            }
12967            final int NI = s.intents.size();
12968            int j;
12969            for (j=0; j<NI; j++) {
12970                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12971                if (DEBUG_SHOW_INFO) {
12972                    Log.v(TAG, "    IntentFilter:");
12973                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12974                }
12975                removeFilter(intent);
12976            }
12977        }
12978
12979        @Override
12980        protected boolean allowFilterResult(
12981                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12982            ServiceInfo filterSi = filter.service.info;
12983            for (int i=dest.size()-1; i>=0; i--) {
12984                ServiceInfo destAi = dest.get(i).serviceInfo;
12985                if (destAi.name == filterSi.name
12986                        && destAi.packageName == filterSi.packageName) {
12987                    return false;
12988                }
12989            }
12990            return true;
12991        }
12992
12993        @Override
12994        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12995            return new PackageParser.ServiceIntentInfo[size];
12996        }
12997
12998        @Override
12999        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13000            if (!sUserManager.exists(userId)) return true;
13001            PackageParser.Package p = filter.service.owner;
13002            if (p != null) {
13003                PackageSetting ps = (PackageSetting)p.mExtras;
13004                if (ps != null) {
13005                    // System apps are never considered stopped for purposes of
13006                    // filtering, because there may be no way for the user to
13007                    // actually re-launch them.
13008                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13009                            && ps.getStopped(userId);
13010                }
13011            }
13012            return false;
13013        }
13014
13015        @Override
13016        protected boolean isPackageForFilter(String packageName,
13017                PackageParser.ServiceIntentInfo info) {
13018            return packageName.equals(info.service.owner.packageName);
13019        }
13020
13021        @Override
13022        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13023                int match, int userId) {
13024            if (!sUserManager.exists(userId)) return null;
13025            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13026            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13027                return null;
13028            }
13029            final PackageParser.Service service = info.service;
13030            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13031            if (ps == null) {
13032                return null;
13033            }
13034            final PackageUserState userState = ps.readUserState(userId);
13035            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13036                    userState, userId);
13037            if (si == null) {
13038                return null;
13039            }
13040            final boolean matchVisibleToInstantApp =
13041                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13042            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13043            // throw out filters that aren't visible to ephemeral apps
13044            if (matchVisibleToInstantApp
13045                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13046                return null;
13047            }
13048            // throw out ephemeral filters if we're not explicitly requesting them
13049            if (!isInstantApp && userState.instantApp) {
13050                return null;
13051            }
13052            // throw out instant app filters if updates are available; will trigger
13053            // instant app resolution
13054            if (userState.instantApp && ps.isUpdateAvailable()) {
13055                return null;
13056            }
13057            final ResolveInfo res = new ResolveInfo();
13058            res.serviceInfo = si;
13059            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13060                res.filter = filter;
13061            }
13062            res.priority = info.getPriority();
13063            res.preferredOrder = service.owner.mPreferredOrder;
13064            res.match = match;
13065            res.isDefault = info.hasDefault;
13066            res.labelRes = info.labelRes;
13067            res.nonLocalizedLabel = info.nonLocalizedLabel;
13068            res.icon = info.icon;
13069            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13070            return res;
13071        }
13072
13073        @Override
13074        protected void sortResults(List<ResolveInfo> results) {
13075            Collections.sort(results, mResolvePrioritySorter);
13076        }
13077
13078        @Override
13079        protected void dumpFilter(PrintWriter out, String prefix,
13080                PackageParser.ServiceIntentInfo filter) {
13081            out.print(prefix); out.print(
13082                    Integer.toHexString(System.identityHashCode(filter.service)));
13083                    out.print(' ');
13084                    filter.service.printComponentShortName(out);
13085                    out.print(" filter ");
13086                    out.print(Integer.toHexString(System.identityHashCode(filter)));
13087                    if (filter.service.info.permission != null) {
13088                        out.print(" permission "); out.println(filter.service.info.permission);
13089                    } else {
13090                        out.println();
13091                    }
13092        }
13093
13094        @Override
13095        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13096            return filter.service;
13097        }
13098
13099        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13100            PackageParser.Service service = (PackageParser.Service)label;
13101            out.print(prefix); out.print(
13102                    Integer.toHexString(System.identityHashCode(service)));
13103                    out.print(' ');
13104                    service.printComponentShortName(out);
13105            if (count > 1) {
13106                out.print(" ("); out.print(count); out.print(" filters)");
13107            }
13108            out.println();
13109        }
13110
13111//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13112//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13113//            final List<ResolveInfo> retList = Lists.newArrayList();
13114//            while (i.hasNext()) {
13115//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13116//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13117//                    retList.add(resolveInfo);
13118//                }
13119//            }
13120//            return retList;
13121//        }
13122
13123        // Keys are String (activity class name), values are Activity.
13124        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13125                = new ArrayMap<ComponentName, PackageParser.Service>();
13126        private int mFlags;
13127    }
13128
13129    private final class ProviderIntentResolver
13130            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13131        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13132                boolean defaultOnly, int userId) {
13133            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13134            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13135        }
13136
13137        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13138                int userId) {
13139            if (!sUserManager.exists(userId))
13140                return null;
13141            mFlags = flags;
13142            return super.queryIntent(intent, resolvedType,
13143                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13144                    userId);
13145        }
13146
13147        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13148                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13149            if (!sUserManager.exists(userId))
13150                return null;
13151            if (packageProviders == null) {
13152                return null;
13153            }
13154            mFlags = flags;
13155            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13156            final int N = packageProviders.size();
13157            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13158                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13159
13160            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13161            for (int i = 0; i < N; ++i) {
13162                intentFilters = packageProviders.get(i).intents;
13163                if (intentFilters != null && intentFilters.size() > 0) {
13164                    PackageParser.ProviderIntentInfo[] array =
13165                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13166                    intentFilters.toArray(array);
13167                    listCut.add(array);
13168                }
13169            }
13170            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13171        }
13172
13173        public final void addProvider(PackageParser.Provider p) {
13174            if (mProviders.containsKey(p.getComponentName())) {
13175                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13176                return;
13177            }
13178
13179            mProviders.put(p.getComponentName(), p);
13180            if (DEBUG_SHOW_INFO) {
13181                Log.v(TAG, "  "
13182                        + (p.info.nonLocalizedLabel != null
13183                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13184                Log.v(TAG, "    Class=" + p.info.name);
13185            }
13186            final int NI = p.intents.size();
13187            int j;
13188            for (j = 0; j < NI; j++) {
13189                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13190                if (DEBUG_SHOW_INFO) {
13191                    Log.v(TAG, "    IntentFilter:");
13192                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13193                }
13194                if (!intent.debugCheck()) {
13195                    Log.w(TAG, "==> For Provider " + p.info.name);
13196                }
13197                addFilter(intent);
13198            }
13199        }
13200
13201        public final void removeProvider(PackageParser.Provider p) {
13202            mProviders.remove(p.getComponentName());
13203            if (DEBUG_SHOW_INFO) {
13204                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13205                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13206                Log.v(TAG, "    Class=" + p.info.name);
13207            }
13208            final int NI = p.intents.size();
13209            int j;
13210            for (j = 0; j < NI; j++) {
13211                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13212                if (DEBUG_SHOW_INFO) {
13213                    Log.v(TAG, "    IntentFilter:");
13214                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13215                }
13216                removeFilter(intent);
13217            }
13218        }
13219
13220        @Override
13221        protected boolean allowFilterResult(
13222                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13223            ProviderInfo filterPi = filter.provider.info;
13224            for (int i = dest.size() - 1; i >= 0; i--) {
13225                ProviderInfo destPi = dest.get(i).providerInfo;
13226                if (destPi.name == filterPi.name
13227                        && destPi.packageName == filterPi.packageName) {
13228                    return false;
13229                }
13230            }
13231            return true;
13232        }
13233
13234        @Override
13235        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13236            return new PackageParser.ProviderIntentInfo[size];
13237        }
13238
13239        @Override
13240        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13241            if (!sUserManager.exists(userId))
13242                return true;
13243            PackageParser.Package p = filter.provider.owner;
13244            if (p != null) {
13245                PackageSetting ps = (PackageSetting) p.mExtras;
13246                if (ps != null) {
13247                    // System apps are never considered stopped for purposes of
13248                    // filtering, because there may be no way for the user to
13249                    // actually re-launch them.
13250                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13251                            && ps.getStopped(userId);
13252                }
13253            }
13254            return false;
13255        }
13256
13257        @Override
13258        protected boolean isPackageForFilter(String packageName,
13259                PackageParser.ProviderIntentInfo info) {
13260            return packageName.equals(info.provider.owner.packageName);
13261        }
13262
13263        @Override
13264        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13265                int match, int userId) {
13266            if (!sUserManager.exists(userId))
13267                return null;
13268            final PackageParser.ProviderIntentInfo info = filter;
13269            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13270                return null;
13271            }
13272            final PackageParser.Provider provider = info.provider;
13273            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13274            if (ps == null) {
13275                return null;
13276            }
13277            final PackageUserState userState = ps.readUserState(userId);
13278            final boolean matchVisibleToInstantApp =
13279                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13280            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13281            // throw out filters that aren't visible to instant applications
13282            if (matchVisibleToInstantApp
13283                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13284                return null;
13285            }
13286            // throw out instant application filters if we're not explicitly requesting them
13287            if (!isInstantApp && userState.instantApp) {
13288                return null;
13289            }
13290            // throw out instant application filters if updates are available; will trigger
13291            // instant application resolution
13292            if (userState.instantApp && ps.isUpdateAvailable()) {
13293                return null;
13294            }
13295            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13296                    userState, userId);
13297            if (pi == null) {
13298                return null;
13299            }
13300            final ResolveInfo res = new ResolveInfo();
13301            res.providerInfo = pi;
13302            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13303                res.filter = filter;
13304            }
13305            res.priority = info.getPriority();
13306            res.preferredOrder = provider.owner.mPreferredOrder;
13307            res.match = match;
13308            res.isDefault = info.hasDefault;
13309            res.labelRes = info.labelRes;
13310            res.nonLocalizedLabel = info.nonLocalizedLabel;
13311            res.icon = info.icon;
13312            res.system = res.providerInfo.applicationInfo.isSystemApp();
13313            return res;
13314        }
13315
13316        @Override
13317        protected void sortResults(List<ResolveInfo> results) {
13318            Collections.sort(results, mResolvePrioritySorter);
13319        }
13320
13321        @Override
13322        protected void dumpFilter(PrintWriter out, String prefix,
13323                PackageParser.ProviderIntentInfo filter) {
13324            out.print(prefix);
13325            out.print(
13326                    Integer.toHexString(System.identityHashCode(filter.provider)));
13327            out.print(' ');
13328            filter.provider.printComponentShortName(out);
13329            out.print(" filter ");
13330            out.println(Integer.toHexString(System.identityHashCode(filter)));
13331        }
13332
13333        @Override
13334        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13335            return filter.provider;
13336        }
13337
13338        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13339            PackageParser.Provider provider = (PackageParser.Provider)label;
13340            out.print(prefix); out.print(
13341                    Integer.toHexString(System.identityHashCode(provider)));
13342                    out.print(' ');
13343                    provider.printComponentShortName(out);
13344            if (count > 1) {
13345                out.print(" ("); out.print(count); out.print(" filters)");
13346            }
13347            out.println();
13348        }
13349
13350        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13351                = new ArrayMap<ComponentName, PackageParser.Provider>();
13352        private int mFlags;
13353    }
13354
13355    static final class InstantAppIntentResolver
13356            extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter,
13357            AuxiliaryResolveInfo.AuxiliaryFilter> {
13358        /**
13359         * The result that has the highest defined order. Ordering applies on a
13360         * per-package basis. Mapping is from package name to Pair of order and
13361         * EphemeralResolveInfo.
13362         * <p>
13363         * NOTE: This is implemented as a field variable for convenience and efficiency.
13364         * By having a field variable, we're able to track filter ordering as soon as
13365         * a non-zero order is defined. Otherwise, multiple loops across the result set
13366         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13367         * this needs to be contained entirely within {@link #filterResults}.
13368         */
13369        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13370
13371        @Override
13372        protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) {
13373            return new AuxiliaryResolveInfo.AuxiliaryFilter[size];
13374        }
13375
13376        @Override
13377        protected boolean isPackageForFilter(String packageName,
13378                AuxiliaryResolveInfo.AuxiliaryFilter responseObj) {
13379            return true;
13380        }
13381
13382        @Override
13383        protected AuxiliaryResolveInfo.AuxiliaryFilter newResult(
13384                AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) {
13385            if (!sUserManager.exists(userId)) {
13386                return null;
13387            }
13388            final String packageName = responseObj.resolveInfo.getPackageName();
13389            final Integer order = responseObj.getOrder();
13390            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13391                    mOrderResult.get(packageName);
13392            // ordering is enabled and this item's order isn't high enough
13393            if (lastOrderResult != null && lastOrderResult.first >= order) {
13394                return null;
13395            }
13396            final InstantAppResolveInfo res = responseObj.resolveInfo;
13397            if (order > 0) {
13398                // non-zero order, enable ordering
13399                mOrderResult.put(packageName, new Pair<>(order, res));
13400            }
13401            return responseObj;
13402        }
13403
13404        @Override
13405        protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) {
13406            // only do work if ordering is enabled [most of the time it won't be]
13407            if (mOrderResult.size() == 0) {
13408                return;
13409            }
13410            int resultSize = results.size();
13411            for (int i = 0; i < resultSize; i++) {
13412                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13413                final String packageName = info.getPackageName();
13414                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13415                if (savedInfo == null) {
13416                    // package doesn't having ordering
13417                    continue;
13418                }
13419                if (savedInfo.second == info) {
13420                    // circled back to the highest ordered item; remove from order list
13421                    mOrderResult.remove(packageName);
13422                    if (mOrderResult.size() == 0) {
13423                        // no more ordered items
13424                        break;
13425                    }
13426                    continue;
13427                }
13428                // item has a worse order, remove it from the result list
13429                results.remove(i);
13430                resultSize--;
13431                i--;
13432            }
13433        }
13434    }
13435
13436    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13437            new Comparator<ResolveInfo>() {
13438        public int compare(ResolveInfo r1, ResolveInfo r2) {
13439            int v1 = r1.priority;
13440            int v2 = r2.priority;
13441            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13442            if (v1 != v2) {
13443                return (v1 > v2) ? -1 : 1;
13444            }
13445            v1 = r1.preferredOrder;
13446            v2 = r2.preferredOrder;
13447            if (v1 != v2) {
13448                return (v1 > v2) ? -1 : 1;
13449            }
13450            if (r1.isDefault != r2.isDefault) {
13451                return r1.isDefault ? -1 : 1;
13452            }
13453            v1 = r1.match;
13454            v2 = r2.match;
13455            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13456            if (v1 != v2) {
13457                return (v1 > v2) ? -1 : 1;
13458            }
13459            if (r1.system != r2.system) {
13460                return r1.system ? -1 : 1;
13461            }
13462            if (r1.activityInfo != null) {
13463                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13464            }
13465            if (r1.serviceInfo != null) {
13466                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13467            }
13468            if (r1.providerInfo != null) {
13469                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13470            }
13471            return 0;
13472        }
13473    };
13474
13475    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13476            new Comparator<ProviderInfo>() {
13477        public int compare(ProviderInfo p1, ProviderInfo p2) {
13478            final int v1 = p1.initOrder;
13479            final int v2 = p2.initOrder;
13480            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13481        }
13482    };
13483
13484    @Override
13485    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13486            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13487            final int[] userIds, int[] instantUserIds) {
13488        mHandler.post(new Runnable() {
13489            @Override
13490            public void run() {
13491                try {
13492                    final IActivityManager am = ActivityManager.getService();
13493                    if (am == null) return;
13494                    final int[] resolvedUserIds;
13495                    if (userIds == null) {
13496                        resolvedUserIds = am.getRunningUserIds();
13497                    } else {
13498                        resolvedUserIds = userIds;
13499                    }
13500                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13501                            resolvedUserIds, false);
13502                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
13503                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13504                                instantUserIds, true);
13505                    }
13506                } catch (RemoteException ex) {
13507                }
13508            }
13509        });
13510    }
13511
13512    @Override
13513    public void notifyPackageAdded(String packageName) {
13514        final PackageListObserver[] observers;
13515        synchronized (mPackages) {
13516            if (mPackageListObservers.size() == 0) {
13517                return;
13518            }
13519            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13520        }
13521        for (int i = observers.length - 1; i >= 0; --i) {
13522            observers[i].onPackageAdded(packageName);
13523        }
13524    }
13525
13526    @Override
13527    public void notifyPackageRemoved(String packageName) {
13528        final PackageListObserver[] observers;
13529        synchronized (mPackages) {
13530            if (mPackageListObservers.size() == 0) {
13531                return;
13532            }
13533            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13534        }
13535        for (int i = observers.length - 1; i >= 0; --i) {
13536            observers[i].onPackageRemoved(packageName);
13537        }
13538    }
13539
13540    /**
13541     * Sends a broadcast for the given action.
13542     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13543     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13544     * the system and applications allowed to see instant applications to receive package
13545     * lifecycle events for instant applications.
13546     */
13547    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13548            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13549            int[] userIds, boolean isInstantApp)
13550                    throws RemoteException {
13551        for (int id : userIds) {
13552            final Intent intent = new Intent(action,
13553                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13554            final String[] requiredPermissions =
13555                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13556            if (extras != null) {
13557                intent.putExtras(extras);
13558            }
13559            if (targetPkg != null) {
13560                intent.setPackage(targetPkg);
13561            }
13562            // Modify the UID when posting to other users
13563            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13564            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13565                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13566                intent.putExtra(Intent.EXTRA_UID, uid);
13567            }
13568            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13569            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13570            if (DEBUG_BROADCASTS) {
13571                RuntimeException here = new RuntimeException("here");
13572                here.fillInStackTrace();
13573                Slog.d(TAG, "Sending to user " + id + ": "
13574                        + intent.toShortString(false, true, false, false)
13575                        + " " + intent.getExtras(), here);
13576            }
13577            am.broadcastIntent(null, intent, null, finishedReceiver,
13578                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13579                    null, finishedReceiver != null, false, id);
13580        }
13581    }
13582
13583    /**
13584     * Check if the external storage media is available. This is true if there
13585     * is a mounted external storage medium or if the external storage is
13586     * emulated.
13587     */
13588    private boolean isExternalMediaAvailable() {
13589        return mMediaMounted || Environment.isExternalStorageEmulated();
13590    }
13591
13592    @Override
13593    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13594        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13595            return null;
13596        }
13597        if (!isExternalMediaAvailable()) {
13598                // If the external storage is no longer mounted at this point,
13599                // the caller may not have been able to delete all of this
13600                // packages files and can not delete any more.  Bail.
13601            return null;
13602        }
13603        synchronized (mPackages) {
13604            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13605            if (lastPackage != null) {
13606                pkgs.remove(lastPackage);
13607            }
13608            if (pkgs.size() > 0) {
13609                return pkgs.get(0);
13610            }
13611        }
13612        return null;
13613    }
13614
13615    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13616        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13617                userId, andCode ? 1 : 0, packageName);
13618        if (mSystemReady) {
13619            msg.sendToTarget();
13620        } else {
13621            if (mPostSystemReadyMessages == null) {
13622                mPostSystemReadyMessages = new ArrayList<>();
13623            }
13624            mPostSystemReadyMessages.add(msg);
13625        }
13626    }
13627
13628    void startCleaningPackages() {
13629        // reader
13630        if (!isExternalMediaAvailable()) {
13631            return;
13632        }
13633        synchronized (mPackages) {
13634            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13635                return;
13636            }
13637        }
13638        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13639        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13640        IActivityManager am = ActivityManager.getService();
13641        if (am != null) {
13642            int dcsUid = -1;
13643            synchronized (mPackages) {
13644                if (!mDefaultContainerWhitelisted) {
13645                    mDefaultContainerWhitelisted = true;
13646                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13647                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13648                }
13649            }
13650            try {
13651                if (dcsUid > 0) {
13652                    am.backgroundWhitelistUid(dcsUid);
13653                }
13654                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13655                        UserHandle.USER_SYSTEM);
13656            } catch (RemoteException e) {
13657            }
13658        }
13659    }
13660
13661    /**
13662     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13663     * it is acting on behalf on an enterprise or the user).
13664     *
13665     * Note that the ordering of the conditionals in this method is important. The checks we perform
13666     * are as follows, in this order:
13667     *
13668     * 1) If the install is being performed by a system app, we can trust the app to have set the
13669     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13670     *    what it is.
13671     * 2) If the install is being performed by a device or profile owner app, the install reason
13672     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13673     *    set the install reason correctly. If the app targets an older SDK version where install
13674     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13675     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13676     * 3) In all other cases, the install is being performed by a regular app that is neither part
13677     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13678     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13679     *    set to enterprise policy and if so, change it to unknown instead.
13680     */
13681    private int fixUpInstallReason(String installerPackageName, int installerUid,
13682            int installReason) {
13683        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13684                == PERMISSION_GRANTED) {
13685            // If the install is being performed by a system app, we trust that app to have set the
13686            // install reason correctly.
13687            return installReason;
13688        }
13689        final String ownerPackage = mProtectedPackages.getDeviceOwnerOrProfileOwnerPackage(
13690                UserHandle.getUserId(installerUid));
13691        if (ownerPackage != null && ownerPackage.equals(installerPackageName)) {
13692            // If the install is being performed by a device or profile owner, the install
13693            // reason should be enterprise policy.
13694            return PackageManager.INSTALL_REASON_POLICY;
13695        }
13696
13697
13698        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13699            // If the install is being performed by a regular app (i.e. neither system app nor
13700            // device or profile owner), we have no reason to believe that the app is acting on
13701            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13702            // change it to unknown instead.
13703            return PackageManager.INSTALL_REASON_UNKNOWN;
13704        }
13705
13706        // If the install is being performed by a regular app and the install reason was set to any
13707        // value but enterprise policy, leave the install reason unchanged.
13708        return installReason;
13709    }
13710
13711    /**
13712     * Attempts to bind to the default container service explicitly instead of doing so lazily on
13713     * install commit.
13714     */
13715    void earlyBindToDefContainer() {
13716        mHandler.sendMessage(mHandler.obtainMessage(DEF_CONTAINER_BIND));
13717    }
13718
13719    void installStage(String packageName, File stagedDir,
13720            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13721            String installerPackageName, int installerUid, UserHandle user,
13722            PackageParser.SigningDetails signingDetails) {
13723        if (DEBUG_INSTANT) {
13724            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13725                Slog.d(TAG, "Ephemeral install of " + packageName);
13726            }
13727        }
13728        final VerificationInfo verificationInfo = new VerificationInfo(
13729                sessionParams.originatingUri, sessionParams.referrerUri,
13730                sessionParams.originatingUid, installerUid);
13731
13732        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13733
13734        final Message msg = mHandler.obtainMessage(INIT_COPY);
13735        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13736                sessionParams.installReason);
13737        final InstallParams params = new InstallParams(origin, null, observer,
13738                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13739                verificationInfo, user, sessionParams.abiOverride,
13740                sessionParams.grantedRuntimePermissions, signingDetails, installReason);
13741        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13742        msg.obj = params;
13743
13744        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13745                System.identityHashCode(msg.obj));
13746        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13747                System.identityHashCode(msg.obj));
13748
13749        mHandler.sendMessage(msg);
13750    }
13751
13752    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13753            int userId) {
13754        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13755        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13756        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13757        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13758        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13759                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13760
13761        // Send a session commit broadcast
13762        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13763        info.installReason = pkgSetting.getInstallReason(userId);
13764        info.appPackageName = packageName;
13765        sendSessionCommitBroadcast(info, userId);
13766    }
13767
13768    @Override
13769    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13770            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13771        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13772            return;
13773        }
13774        Bundle extras = new Bundle(1);
13775        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13776        final int uid = UserHandle.getUid(
13777                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13778        extras.putInt(Intent.EXTRA_UID, uid);
13779
13780        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13781                packageName, extras, 0, null, null, userIds, instantUserIds);
13782        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13783            mHandler.post(() -> {
13784                        for (int userId : userIds) {
13785                            sendBootCompletedBroadcastToSystemApp(
13786                                    packageName, includeStopped, userId);
13787                        }
13788                    }
13789            );
13790        }
13791    }
13792
13793    /**
13794     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13795     * automatically without needing an explicit launch.
13796     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13797     */
13798    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13799            int userId) {
13800        // If user is not running, the app didn't miss any broadcast
13801        if (!mUserManagerInternal.isUserRunning(userId)) {
13802            return;
13803        }
13804        final IActivityManager am = ActivityManager.getService();
13805        try {
13806            // Deliver LOCKED_BOOT_COMPLETED first
13807            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13808                    .setPackage(packageName);
13809            if (includeStopped) {
13810                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13811            }
13812            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13813            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13814                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13815
13816            // Deliver BOOT_COMPLETED only if user is unlocked
13817            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13818                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13819                if (includeStopped) {
13820                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13821                }
13822                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13823                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13824            }
13825        } catch (RemoteException e) {
13826            throw e.rethrowFromSystemServer();
13827        }
13828    }
13829
13830    @Override
13831    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13832            int userId) {
13833        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13834        PackageSetting pkgSetting;
13835        final int callingUid = Binder.getCallingUid();
13836        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13837                true /* requireFullPermission */, true /* checkShell */,
13838                "setApplicationHiddenSetting for user " + userId);
13839
13840        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13841            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13842            return false;
13843        }
13844
13845        long callingId = Binder.clearCallingIdentity();
13846        try {
13847            boolean sendAdded = false;
13848            boolean sendRemoved = false;
13849            // writer
13850            synchronized (mPackages) {
13851                pkgSetting = mSettings.mPackages.get(packageName);
13852                if (pkgSetting == null) {
13853                    return false;
13854                }
13855                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13856                    return false;
13857                }
13858                // Do not allow "android" is being disabled
13859                if ("android".equals(packageName)) {
13860                    Slog.w(TAG, "Cannot hide package: android");
13861                    return false;
13862                }
13863                // Cannot hide static shared libs as they are considered
13864                // a part of the using app (emulating static linking). Also
13865                // static libs are installed always on internal storage.
13866                PackageParser.Package pkg = mPackages.get(packageName);
13867                if (pkg != null && pkg.staticSharedLibName != null) {
13868                    Slog.w(TAG, "Cannot hide package: " + packageName
13869                            + " providing static shared library: "
13870                            + pkg.staticSharedLibName);
13871                    return false;
13872                }
13873                // Only allow protected packages to hide themselves.
13874                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13875                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13876                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13877                    return false;
13878                }
13879
13880                if (pkgSetting.getHidden(userId) != hidden) {
13881                    pkgSetting.setHidden(hidden, userId);
13882                    mSettings.writePackageRestrictionsLPr(userId);
13883                    if (hidden) {
13884                        sendRemoved = true;
13885                    } else {
13886                        sendAdded = true;
13887                    }
13888                }
13889            }
13890            if (sendAdded) {
13891                sendPackageAddedForUser(packageName, pkgSetting, userId);
13892                return true;
13893            }
13894            if (sendRemoved) {
13895                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13896                        "hiding pkg");
13897                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13898                return true;
13899            }
13900        } finally {
13901            Binder.restoreCallingIdentity(callingId);
13902        }
13903        return false;
13904    }
13905
13906    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13907            int userId) {
13908        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13909        info.removedPackage = packageName;
13910        info.installerPackageName = pkgSetting.installerPackageName;
13911        info.removedUsers = new int[] {userId};
13912        info.broadcastUsers = new int[] {userId};
13913        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13914        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13915    }
13916
13917    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended,
13918            PersistableBundle launcherExtras) {
13919        if (pkgList.length > 0) {
13920            Bundle extras = new Bundle(1);
13921            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13922            if (launcherExtras != null) {
13923                extras.putBundle(Intent.EXTRA_LAUNCHER_EXTRAS,
13924                        new Bundle(launcherExtras.deepCopy()));
13925            }
13926            sendPackageBroadcast(
13927                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13928                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13929                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13930                    new int[] {userId}, null);
13931        }
13932    }
13933
13934    /**
13935     * Returns true if application is not found or there was an error. Otherwise it returns
13936     * the hidden state of the package for the given user.
13937     */
13938    @Override
13939    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13940        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13941        final int callingUid = Binder.getCallingUid();
13942        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13943                true /* requireFullPermission */, false /* checkShell */,
13944                "getApplicationHidden for user " + userId);
13945        PackageSetting ps;
13946        long callingId = Binder.clearCallingIdentity();
13947        try {
13948            // writer
13949            synchronized (mPackages) {
13950                ps = mSettings.mPackages.get(packageName);
13951                if (ps == null) {
13952                    return true;
13953                }
13954                if (filterAppAccessLPr(ps, callingUid, userId)) {
13955                    return true;
13956                }
13957                return ps.getHidden(userId);
13958            }
13959        } finally {
13960            Binder.restoreCallingIdentity(callingId);
13961        }
13962    }
13963
13964    /**
13965     * @hide
13966     */
13967    @Override
13968    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13969            int installReason) {
13970        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13971                null);
13972        PackageSetting pkgSetting;
13973        final int callingUid = Binder.getCallingUid();
13974        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13975                true /* requireFullPermission */, true /* checkShell */,
13976                "installExistingPackage for user " + userId);
13977        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13978            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13979        }
13980
13981        long callingId = Binder.clearCallingIdentity();
13982        try {
13983            boolean installed = false;
13984            final boolean instantApp =
13985                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13986            final boolean fullApp =
13987                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13988
13989            // writer
13990            synchronized (mPackages) {
13991                pkgSetting = mSettings.mPackages.get(packageName);
13992                if (pkgSetting == null) {
13993                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13994                }
13995                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13996                    // only allow the existing package to be used if it's installed as a full
13997                    // application for at least one user
13998                    boolean installAllowed = false;
13999                    for (int checkUserId : sUserManager.getUserIds()) {
14000                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14001                        if (installAllowed) {
14002                            break;
14003                        }
14004                    }
14005                    if (!installAllowed) {
14006                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14007                    }
14008                }
14009                if (!pkgSetting.getInstalled(userId)) {
14010                    pkgSetting.setInstalled(true, userId);
14011                    pkgSetting.setHidden(false, userId);
14012                    pkgSetting.setInstallReason(installReason, userId);
14013                    mSettings.writePackageRestrictionsLPr(userId);
14014                    mSettings.writeKernelMappingLPr(pkgSetting);
14015                    installed = true;
14016                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14017                    // upgrade app from instant to full; we don't allow app downgrade
14018                    installed = true;
14019                }
14020                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14021            }
14022
14023            if (installed) {
14024                if (pkgSetting.pkg != null) {
14025                    synchronized (mInstallLock) {
14026                        // We don't need to freeze for a brand new install
14027                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14028                    }
14029                }
14030                sendPackageAddedForUser(packageName, pkgSetting, userId);
14031                synchronized (mPackages) {
14032                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14033                }
14034            }
14035        } finally {
14036            Binder.restoreCallingIdentity(callingId);
14037        }
14038
14039        return PackageManager.INSTALL_SUCCEEDED;
14040    }
14041
14042    static void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14043            boolean instantApp, boolean fullApp) {
14044        // no state specified; do nothing
14045        if (!instantApp && !fullApp) {
14046            return;
14047        }
14048        if (userId != UserHandle.USER_ALL) {
14049            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14050                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14051            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14052                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14053            }
14054        } else {
14055            for (int currentUserId : sUserManager.getUserIds()) {
14056                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14057                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14058                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14059                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14060                }
14061            }
14062        }
14063    }
14064
14065    boolean isUserRestricted(int userId, String restrictionKey) {
14066        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14067        if (restrictions.getBoolean(restrictionKey, false)) {
14068            Log.w(TAG, "User is restricted: " + restrictionKey);
14069            return true;
14070        }
14071        return false;
14072    }
14073
14074    @Override
14075    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14076            PersistableBundle appExtras, PersistableBundle launcherExtras, String dialogMessage,
14077            String callingPackage, int userId) {
14078        try {
14079            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.SUSPEND_APPS, null);
14080        } catch (SecurityException e) {
14081            mContext.enforceCallingOrSelfPermission(Manifest.permission.MANAGE_USERS,
14082                    "Callers need to have either " + Manifest.permission.SUSPEND_APPS + " or "
14083                            + Manifest.permission.MANAGE_USERS);
14084        }
14085        final int callingUid = Binder.getCallingUid();
14086        if (callingUid != Process.ROOT_UID && callingUid != Process.SYSTEM_UID
14087                && getPackageUid(callingPackage, 0, userId) != callingUid) {
14088            throw new SecurityException("Calling package " + callingPackage + " in user "
14089                    + userId + " does not belong to calling uid " + callingUid);
14090        }
14091        if (!PLATFORM_PACKAGE_NAME.equals(callingPackage)
14092                && mProtectedPackages.getDeviceOwnerOrProfileOwnerPackage(userId) != null) {
14093            throw new UnsupportedOperationException("Cannot suspend/unsuspend packages. User "
14094                    + userId + " has an active DO or PO");
14095        }
14096        if (ArrayUtils.isEmpty(packageNames)) {
14097            return packageNames;
14098        }
14099
14100        final List<String> changedPackagesList = new ArrayList<>(packageNames.length);
14101        final List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14102        final long callingId = Binder.clearCallingIdentity();
14103        try {
14104            synchronized (mPackages) {
14105                for (int i = 0; i < packageNames.length; i++) {
14106                    final String packageName = packageNames[i];
14107                    if (callingPackage.equals(packageName)) {
14108                        Slog.w(TAG, "Calling package: " + callingPackage + " trying to "
14109                                + (suspended ? "" : "un") + "suspend itself. Ignoring");
14110                        unactionedPackages.add(packageName);
14111                        continue;
14112                    }
14113                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14114                    if (pkgSetting == null
14115                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14116                        Slog.w(TAG, "Could not find package setting for package: " + packageName
14117                                + ". Skipping suspending/un-suspending.");
14118                        unactionedPackages.add(packageName);
14119                        continue;
14120                    }
14121                    if (!canSuspendPackageForUserLocked(packageName, userId)) {
14122                        unactionedPackages.add(packageName);
14123                        continue;
14124                    }
14125                    pkgSetting.setSuspended(suspended, callingPackage, dialogMessage, appExtras,
14126                            launcherExtras, userId);
14127                    changedPackagesList.add(packageName);
14128                }
14129            }
14130        } finally {
14131            Binder.restoreCallingIdentity(callingId);
14132        }
14133        if (!changedPackagesList.isEmpty()) {
14134            final String[] changedPackages = changedPackagesList.toArray(
14135                    new String[changedPackagesList.size()]);
14136            sendPackagesSuspendedForUser(changedPackages, userId, suspended, launcherExtras);
14137            sendMyPackageSuspendedOrUnsuspended(changedPackages, suspended, appExtras, userId);
14138            synchronized (mPackages) {
14139                scheduleWritePackageRestrictionsLocked(userId);
14140            }
14141        }
14142        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14143    }
14144
14145    @Override
14146    public PersistableBundle getSuspendedPackageAppExtras(String packageName, int userId) {
14147        final int callingUid = Binder.getCallingUid();
14148        if (getPackageUid(packageName, 0, userId) != callingUid) {
14149            throw new SecurityException("Calling package " + packageName
14150                    + " does not belong to calling uid " + callingUid);
14151        }
14152        synchronized (mPackages) {
14153            final PackageSetting ps = mSettings.mPackages.get(packageName);
14154            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14155                throw new IllegalArgumentException("Unknown target package: " + packageName);
14156            }
14157            final PackageUserState packageUserState = ps.readUserState(userId);
14158            if (packageUserState.suspended) {
14159                return packageUserState.suspendedAppExtras;
14160            }
14161            return null;
14162        }
14163    }
14164
14165    private void sendMyPackageSuspendedOrUnsuspended(String[] affectedPackages, boolean suspended,
14166            PersistableBundle appExtras, int userId) {
14167        final String action;
14168        final Bundle intentExtras = new Bundle();
14169        if (suspended) {
14170            action = Intent.ACTION_MY_PACKAGE_SUSPENDED;
14171            if (appExtras != null) {
14172                final Bundle bundledAppExtras = new Bundle(appExtras.deepCopy());
14173                intentExtras.putBundle(Intent.EXTRA_SUSPENDED_PACKAGE_EXTRAS, bundledAppExtras);
14174            }
14175        } else {
14176            action = Intent.ACTION_MY_PACKAGE_UNSUSPENDED;
14177        }
14178        mHandler.post(new Runnable() {
14179            @Override
14180            public void run() {
14181                try {
14182                    final IActivityManager am = ActivityManager.getService();
14183                    if (am == null) {
14184                        Slog.wtf(TAG, "IActivityManager null. Cannot send MY_PACKAGE_ "
14185                                + (suspended ? "" : "UN") + "SUSPENDED broadcasts");
14186                        return;
14187                    }
14188                    final int[] targetUserIds = new int[] {userId};
14189                    for (String packageName : affectedPackages) {
14190                        doSendBroadcast(am, action, null, intentExtras,
14191                                Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, packageName, null,
14192                                targetUserIds, false);
14193                    }
14194                } catch (RemoteException ex) {
14195                    // Shouldn't happen as AMS is in the same process.
14196                }
14197            }
14198        });
14199    }
14200
14201    @Override
14202    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14203        final int callingUid = Binder.getCallingUid();
14204        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14205                true /* requireFullPermission */, false /* checkShell */,
14206                "isPackageSuspendedForUser for user " + userId);
14207        synchronized (mPackages) {
14208            final PackageSetting ps = mSettings.mPackages.get(packageName);
14209            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14210                throw new IllegalArgumentException("Unknown target package: " + packageName);
14211            }
14212            return ps.getSuspended(userId);
14213        }
14214    }
14215
14216    /**
14217     * Immediately unsuspends any packages suspended by the given package. To be called
14218     * when such a package's data is cleared or it is removed from the device.
14219     *
14220     * <p><b>Should not be used on a frequent code path</b> as it flushes state to disk
14221     * synchronously
14222     *
14223     * @param packageName The package holding {@link Manifest.permission#SUSPEND_APPS} permission
14224     * @param affectedUser The user for which the changes are taking place.
14225     */
14226    void unsuspendForSuspendingPackage(String packageName, int affectedUser) {
14227        final int[] userIds = (affectedUser == UserHandle.USER_ALL) ? sUserManager.getUserIds()
14228                : new int[] {affectedUser};
14229        for (int userId : userIds) {
14230            List<String> affectedPackages = new ArrayList<>();
14231            synchronized (mPackages) {
14232                for (PackageSetting ps : mSettings.mPackages.values()) {
14233                    final PackageUserState pus = ps.readUserState(userId);
14234                    if (pus.suspended && packageName.equals(pus.suspendingPackage)) {
14235                        ps.setSuspended(false, null, null, null, null, userId);
14236                        affectedPackages.add(ps.name);
14237                    }
14238                }
14239            }
14240            if (!affectedPackages.isEmpty()) {
14241                final String[] packageArray = affectedPackages.toArray(
14242                        new String[affectedPackages.size()]);
14243                sendMyPackageSuspendedOrUnsuspended(packageArray, false, null, userId);
14244                sendPackagesSuspendedForUser(packageArray, userId, false, null);
14245                // Write package restrictions immediately to avoid an inconsistent state.
14246                mSettings.writePackageRestrictionsLPr(userId);
14247            }
14248        }
14249    }
14250
14251    @GuardedBy("mPackages")
14252    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14253        if (isPackageDeviceAdmin(packageName, userId)) {
14254            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14255                    + "\": has an active device admin");
14256            return false;
14257        }
14258
14259        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14260        if (packageName.equals(activeLauncherPackageName)) {
14261            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14262                    + "\": contains the active launcher");
14263            return false;
14264        }
14265
14266        if (packageName.equals(mRequiredInstallerPackage)) {
14267            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14268                    + "\": required for package installation");
14269            return false;
14270        }
14271
14272        if (packageName.equals(mRequiredUninstallerPackage)) {
14273            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14274                    + "\": required for package uninstallation");
14275            return false;
14276        }
14277
14278        if (packageName.equals(mRequiredVerifierPackage)) {
14279            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14280                    + "\": required for package verification");
14281            return false;
14282        }
14283
14284        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14285            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14286                    + "\": is the default dialer");
14287            return false;
14288        }
14289
14290        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14291            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14292                    + "\": protected package");
14293            return false;
14294        }
14295
14296        // Cannot suspend static shared libs as they are considered
14297        // a part of the using app (emulating static linking). Also
14298        // static libs are installed always on internal storage.
14299        PackageParser.Package pkg = mPackages.get(packageName);
14300        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14301            Slog.w(TAG, "Cannot suspend package: " + packageName
14302                    + " providing static shared library: "
14303                    + pkg.staticSharedLibName);
14304            return false;
14305        }
14306
14307        if (PLATFORM_PACKAGE_NAME.equals(packageName)) {
14308            Slog.w(TAG, "Cannot suspend package: " + packageName);
14309            return false;
14310        }
14311
14312        return true;
14313    }
14314
14315    private String getActiveLauncherPackageName(int userId) {
14316        Intent intent = new Intent(Intent.ACTION_MAIN);
14317        intent.addCategory(Intent.CATEGORY_HOME);
14318        ResolveInfo resolveInfo = resolveIntent(
14319                intent,
14320                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14321                PackageManager.MATCH_DEFAULT_ONLY,
14322                userId);
14323
14324        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14325    }
14326
14327    private String getDefaultDialerPackageName(int userId) {
14328        synchronized (mPackages) {
14329            return mSettings.getDefaultDialerPackageNameLPw(userId);
14330        }
14331    }
14332
14333    @Override
14334    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14335        mContext.enforceCallingOrSelfPermission(
14336                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14337                "Only package verification agents can verify applications");
14338
14339        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14340        final PackageVerificationResponse response = new PackageVerificationResponse(
14341                verificationCode, Binder.getCallingUid());
14342        msg.arg1 = id;
14343        msg.obj = response;
14344        mHandler.sendMessage(msg);
14345    }
14346
14347    @Override
14348    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14349            long millisecondsToDelay) {
14350        mContext.enforceCallingOrSelfPermission(
14351                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14352                "Only package verification agents can extend verification timeouts");
14353
14354        final PackageVerificationState state = mPendingVerification.get(id);
14355        final PackageVerificationResponse response = new PackageVerificationResponse(
14356                verificationCodeAtTimeout, Binder.getCallingUid());
14357
14358        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14359            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14360        }
14361        if (millisecondsToDelay < 0) {
14362            millisecondsToDelay = 0;
14363        }
14364        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14365                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14366            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14367        }
14368
14369        if ((state != null) && !state.timeoutExtended()) {
14370            state.extendTimeout();
14371
14372            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14373            msg.arg1 = id;
14374            msg.obj = response;
14375            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14376        }
14377    }
14378
14379    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14380            int verificationCode, UserHandle user) {
14381        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14382        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14383        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14384        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14385        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14386
14387        mContext.sendBroadcastAsUser(intent, user,
14388                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14389    }
14390
14391    private ComponentName matchComponentForVerifier(String packageName,
14392            List<ResolveInfo> receivers) {
14393        ActivityInfo targetReceiver = null;
14394
14395        final int NR = receivers.size();
14396        for (int i = 0; i < NR; i++) {
14397            final ResolveInfo info = receivers.get(i);
14398            if (info.activityInfo == null) {
14399                continue;
14400            }
14401
14402            if (packageName.equals(info.activityInfo.packageName)) {
14403                targetReceiver = info.activityInfo;
14404                break;
14405            }
14406        }
14407
14408        if (targetReceiver == null) {
14409            return null;
14410        }
14411
14412        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14413    }
14414
14415    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14416            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14417        if (pkgInfo.verifiers.length == 0) {
14418            return null;
14419        }
14420
14421        final int N = pkgInfo.verifiers.length;
14422        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14423        for (int i = 0; i < N; i++) {
14424            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14425
14426            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14427                    receivers);
14428            if (comp == null) {
14429                continue;
14430            }
14431
14432            final int verifierUid = getUidForVerifier(verifierInfo);
14433            if (verifierUid == -1) {
14434                continue;
14435            }
14436
14437            if (DEBUG_VERIFY) {
14438                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14439                        + " with the correct signature");
14440            }
14441            sufficientVerifiers.add(comp);
14442            verificationState.addSufficientVerifier(verifierUid);
14443        }
14444
14445        return sufficientVerifiers;
14446    }
14447
14448    private int getUidForVerifier(VerifierInfo verifierInfo) {
14449        synchronized (mPackages) {
14450            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14451            if (pkg == null) {
14452                return -1;
14453            } else if (pkg.mSigningDetails.signatures.length != 1) {
14454                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14455                        + " has more than one signature; ignoring");
14456                return -1;
14457            }
14458
14459            /*
14460             * If the public key of the package's signature does not match
14461             * our expected public key, then this is a different package and
14462             * we should skip.
14463             */
14464
14465            final byte[] expectedPublicKey;
14466            try {
14467                final Signature verifierSig = pkg.mSigningDetails.signatures[0];
14468                final PublicKey publicKey = verifierSig.getPublicKey();
14469                expectedPublicKey = publicKey.getEncoded();
14470            } catch (CertificateException e) {
14471                return -1;
14472            }
14473
14474            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14475
14476            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14477                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14478                        + " does not have the expected public key; ignoring");
14479                return -1;
14480            }
14481
14482            return pkg.applicationInfo.uid;
14483        }
14484    }
14485
14486    @Override
14487    public void finishPackageInstall(int token, boolean didLaunch) {
14488        enforceSystemOrRoot("Only the system is allowed to finish installs");
14489
14490        if (DEBUG_INSTALL) {
14491            Slog.v(TAG, "BM finishing package install for " + token);
14492        }
14493        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14494
14495        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14496        mHandler.sendMessage(msg);
14497    }
14498
14499    /**
14500     * Get the verification agent timeout.  Used for both the APK verifier and the
14501     * intent filter verifier.
14502     *
14503     * @return verification timeout in milliseconds
14504     */
14505    private long getVerificationTimeout() {
14506        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14507                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14508                DEFAULT_VERIFICATION_TIMEOUT);
14509    }
14510
14511    /**
14512     * Get the default verification agent response code.
14513     *
14514     * @return default verification response code
14515     */
14516    private int getDefaultVerificationResponse(UserHandle user) {
14517        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14518            return PackageManager.VERIFICATION_REJECT;
14519        }
14520        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14521                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14522                DEFAULT_VERIFICATION_RESPONSE);
14523    }
14524
14525    /**
14526     * Check whether or not package verification has been enabled.
14527     *
14528     * @return true if verification should be performed
14529     */
14530    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14531        if (!DEFAULT_VERIFY_ENABLE) {
14532            return false;
14533        }
14534
14535        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14536
14537        // Check if installing from ADB
14538        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14539            // Do not run verification in a test harness environment
14540            if (ActivityManager.isRunningInTestHarness()) {
14541                return false;
14542            }
14543            if (ensureVerifyAppsEnabled) {
14544                return true;
14545            }
14546            // Check if the developer does not want package verification for ADB installs
14547            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14548                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14549                return false;
14550            }
14551        } else {
14552            // only when not installed from ADB, skip verification for instant apps when
14553            // the installer and verifier are the same.
14554            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14555                if (mInstantAppInstallerActivity != null
14556                        && mInstantAppInstallerActivity.packageName.equals(
14557                                mRequiredVerifierPackage)) {
14558                    try {
14559                        mContext.getSystemService(AppOpsManager.class)
14560                                .checkPackage(installerUid, mRequiredVerifierPackage);
14561                        if (DEBUG_VERIFY) {
14562                            Slog.i(TAG, "disable verification for instant app");
14563                        }
14564                        return false;
14565                    } catch (SecurityException ignore) { }
14566                }
14567            }
14568        }
14569
14570        if (ensureVerifyAppsEnabled) {
14571            return true;
14572        }
14573
14574        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14575                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14576    }
14577
14578    @Override
14579    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14580            throws RemoteException {
14581        mContext.enforceCallingOrSelfPermission(
14582                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14583                "Only intentfilter verification agents can verify applications");
14584
14585        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14586        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14587                Binder.getCallingUid(), verificationCode, failedDomains);
14588        msg.arg1 = id;
14589        msg.obj = response;
14590        mHandler.sendMessage(msg);
14591    }
14592
14593    @Override
14594    public int getIntentVerificationStatus(String packageName, int userId) {
14595        final int callingUid = Binder.getCallingUid();
14596        if (UserHandle.getUserId(callingUid) != userId) {
14597            mContext.enforceCallingOrSelfPermission(
14598                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14599                    "getIntentVerificationStatus" + userId);
14600        }
14601        if (getInstantAppPackageName(callingUid) != null) {
14602            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14603        }
14604        synchronized (mPackages) {
14605            final PackageSetting ps = mSettings.mPackages.get(packageName);
14606            if (ps == null
14607                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14608                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14609            }
14610            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14611        }
14612    }
14613
14614    @Override
14615    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14616        mContext.enforceCallingOrSelfPermission(
14617                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14618
14619        boolean result = false;
14620        synchronized (mPackages) {
14621            final PackageSetting ps = mSettings.mPackages.get(packageName);
14622            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14623                return false;
14624            }
14625            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14626        }
14627        if (result) {
14628            scheduleWritePackageRestrictionsLocked(userId);
14629        }
14630        return result;
14631    }
14632
14633    @Override
14634    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14635            String packageName) {
14636        final int callingUid = Binder.getCallingUid();
14637        if (getInstantAppPackageName(callingUid) != null) {
14638            return ParceledListSlice.emptyList();
14639        }
14640        synchronized (mPackages) {
14641            final PackageSetting ps = mSettings.mPackages.get(packageName);
14642            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14643                return ParceledListSlice.emptyList();
14644            }
14645            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14646        }
14647    }
14648
14649    @Override
14650    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14651        if (TextUtils.isEmpty(packageName)) {
14652            return ParceledListSlice.emptyList();
14653        }
14654        final int callingUid = Binder.getCallingUid();
14655        final int callingUserId = UserHandle.getUserId(callingUid);
14656        synchronized (mPackages) {
14657            PackageParser.Package pkg = mPackages.get(packageName);
14658            if (pkg == null || pkg.activities == null) {
14659                return ParceledListSlice.emptyList();
14660            }
14661            if (pkg.mExtras == null) {
14662                return ParceledListSlice.emptyList();
14663            }
14664            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14665            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14666                return ParceledListSlice.emptyList();
14667            }
14668            final int count = pkg.activities.size();
14669            ArrayList<IntentFilter> result = new ArrayList<>();
14670            for (int n=0; n<count; n++) {
14671                PackageParser.Activity activity = pkg.activities.get(n);
14672                if (activity.intents != null && activity.intents.size() > 0) {
14673                    result.addAll(activity.intents);
14674                }
14675            }
14676            return new ParceledListSlice<>(result);
14677        }
14678    }
14679
14680    @Override
14681    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14682        mContext.enforceCallingOrSelfPermission(
14683                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14684        if (UserHandle.getCallingUserId() != userId) {
14685            mContext.enforceCallingOrSelfPermission(
14686                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14687        }
14688
14689        synchronized (mPackages) {
14690            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14691            if (packageName != null) {
14692                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14693                        packageName, userId);
14694            }
14695            return result;
14696        }
14697    }
14698
14699    @Override
14700    public String getDefaultBrowserPackageName(int userId) {
14701        if (UserHandle.getCallingUserId() != userId) {
14702            mContext.enforceCallingOrSelfPermission(
14703                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14704        }
14705        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14706            return null;
14707        }
14708        synchronized (mPackages) {
14709            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14710        }
14711    }
14712
14713    /**
14714     * Get the "allow unknown sources" setting.
14715     *
14716     * @return the current "allow unknown sources" setting
14717     */
14718    private int getUnknownSourcesSettings() {
14719        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14720                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14721                -1);
14722    }
14723
14724    @Override
14725    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14726        final int callingUid = Binder.getCallingUid();
14727        if (getInstantAppPackageName(callingUid) != null) {
14728            return;
14729        }
14730        // writer
14731        synchronized (mPackages) {
14732            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14733            if (targetPackageSetting == null
14734                    || filterAppAccessLPr(
14735                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14736                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14737            }
14738
14739            PackageSetting installerPackageSetting;
14740            if (installerPackageName != null) {
14741                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14742                if (installerPackageSetting == null) {
14743                    throw new IllegalArgumentException("Unknown installer package: "
14744                            + installerPackageName);
14745                }
14746            } else {
14747                installerPackageSetting = null;
14748            }
14749
14750            Signature[] callerSignature;
14751            Object obj = mSettings.getUserIdLPr(callingUid);
14752            if (obj != null) {
14753                if (obj instanceof SharedUserSetting) {
14754                    callerSignature =
14755                            ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
14756                } else if (obj instanceof PackageSetting) {
14757                    callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
14758                } else {
14759                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14760                }
14761            } else {
14762                throw new SecurityException("Unknown calling UID: " + callingUid);
14763            }
14764
14765            // Verify: can't set installerPackageName to a package that is
14766            // not signed with the same cert as the caller.
14767            if (installerPackageSetting != null) {
14768                if (compareSignatures(callerSignature,
14769                        installerPackageSetting.signatures.mSigningDetails.signatures)
14770                        != PackageManager.SIGNATURE_MATCH) {
14771                    throw new SecurityException(
14772                            "Caller does not have same cert as new installer package "
14773                            + installerPackageName);
14774                }
14775            }
14776
14777            // Verify: if target already has an installer package, it must
14778            // be signed with the same cert as the caller.
14779            if (targetPackageSetting.installerPackageName != null) {
14780                PackageSetting setting = mSettings.mPackages.get(
14781                        targetPackageSetting.installerPackageName);
14782                // If the currently set package isn't valid, then it's always
14783                // okay to change it.
14784                if (setting != null) {
14785                    if (compareSignatures(callerSignature,
14786                            setting.signatures.mSigningDetails.signatures)
14787                            != PackageManager.SIGNATURE_MATCH) {
14788                        throw new SecurityException(
14789                                "Caller does not have same cert as old installer package "
14790                                + targetPackageSetting.installerPackageName);
14791                    }
14792                }
14793            }
14794
14795            // Okay!
14796            targetPackageSetting.installerPackageName = installerPackageName;
14797            if (installerPackageName != null) {
14798                mSettings.mInstallerPackages.add(installerPackageName);
14799            }
14800            scheduleWriteSettingsLocked();
14801        }
14802    }
14803
14804    @Override
14805    public void setApplicationCategoryHint(String packageName, int categoryHint,
14806            String callerPackageName) {
14807        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14808            throw new SecurityException("Instant applications don't have access to this method");
14809        }
14810        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14811                callerPackageName);
14812        synchronized (mPackages) {
14813            PackageSetting ps = mSettings.mPackages.get(packageName);
14814            if (ps == null) {
14815                throw new IllegalArgumentException("Unknown target package " + packageName);
14816            }
14817            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14818                throw new IllegalArgumentException("Unknown target package " + packageName);
14819            }
14820            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14821                throw new IllegalArgumentException("Calling package " + callerPackageName
14822                        + " is not installer for " + packageName);
14823            }
14824
14825            if (ps.categoryHint != categoryHint) {
14826                ps.categoryHint = categoryHint;
14827                scheduleWriteSettingsLocked();
14828            }
14829        }
14830    }
14831
14832    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14833        // Queue up an async operation since the package installation may take a little while.
14834        mHandler.post(new Runnable() {
14835            public void run() {
14836                mHandler.removeCallbacks(this);
14837                 // Result object to be returned
14838                PackageInstalledInfo res = new PackageInstalledInfo();
14839                res.setReturnCode(currentStatus);
14840                res.uid = -1;
14841                res.pkg = null;
14842                res.removedInfo = null;
14843                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14844                    args.doPreInstall(res.returnCode);
14845                    synchronized (mInstallLock) {
14846                        installPackageTracedLI(args, res);
14847                    }
14848                    args.doPostInstall(res.returnCode, res.uid);
14849                }
14850
14851                // A restore should be performed at this point if (a) the install
14852                // succeeded, (b) the operation is not an update, and (c) the new
14853                // package has not opted out of backup participation.
14854                final boolean update = res.removedInfo != null
14855                        && res.removedInfo.removedPackage != null;
14856                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14857                boolean doRestore = !update
14858                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14859
14860                // Set up the post-install work request bookkeeping.  This will be used
14861                // and cleaned up by the post-install event handling regardless of whether
14862                // there's a restore pass performed.  Token values are >= 1.
14863                int token;
14864                if (mNextInstallToken < 0) mNextInstallToken = 1;
14865                token = mNextInstallToken++;
14866
14867                PostInstallData data = new PostInstallData(args, res);
14868                mRunningInstalls.put(token, data);
14869                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14870
14871                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14872                    // Pass responsibility to the Backup Manager.  It will perform a
14873                    // restore if appropriate, then pass responsibility back to the
14874                    // Package Manager to run the post-install observer callbacks
14875                    // and broadcasts.
14876                    IBackupManager bm = IBackupManager.Stub.asInterface(
14877                            ServiceManager.getService(Context.BACKUP_SERVICE));
14878                    if (bm != null) {
14879                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14880                                + " to BM for possible restore");
14881                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14882                        try {
14883                            // TODO: http://b/22388012
14884                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14885                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14886                            } else {
14887                                doRestore = false;
14888                            }
14889                        } catch (RemoteException e) {
14890                            // can't happen; the backup manager is local
14891                        } catch (Exception e) {
14892                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14893                            doRestore = false;
14894                        }
14895                    } else {
14896                        Slog.e(TAG, "Backup Manager not found!");
14897                        doRestore = false;
14898                    }
14899                }
14900
14901                if (!doRestore) {
14902                    // No restore possible, or the Backup Manager was mysteriously not
14903                    // available -- just fire the post-install work request directly.
14904                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14905
14906                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14907
14908                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14909                    mHandler.sendMessage(msg);
14910                }
14911            }
14912        });
14913    }
14914
14915    /**
14916     * Callback from PackageSettings whenever an app is first transitioned out of the
14917     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14918     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14919     * here whether the app is the target of an ongoing install, and only send the
14920     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14921     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14922     * handling.
14923     */
14924    void notifyFirstLaunch(final String packageName, final String installerPackage,
14925            final int userId) {
14926        // Serialize this with the rest of the install-process message chain.  In the
14927        // restore-at-install case, this Runnable will necessarily run before the
14928        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14929        // are coherent.  In the non-restore case, the app has already completed install
14930        // and been launched through some other means, so it is not in a problematic
14931        // state for observers to see the FIRST_LAUNCH signal.
14932        mHandler.post(new Runnable() {
14933            @Override
14934            public void run() {
14935                for (int i = 0; i < mRunningInstalls.size(); i++) {
14936                    final PostInstallData data = mRunningInstalls.valueAt(i);
14937                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14938                        continue;
14939                    }
14940                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14941                        // right package; but is it for the right user?
14942                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14943                            if (userId == data.res.newUsers[uIndex]) {
14944                                if (DEBUG_BACKUP) {
14945                                    Slog.i(TAG, "Package " + packageName
14946                                            + " being restored so deferring FIRST_LAUNCH");
14947                                }
14948                                return;
14949                            }
14950                        }
14951                    }
14952                }
14953                // didn't find it, so not being restored
14954                if (DEBUG_BACKUP) {
14955                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14956                }
14957                final boolean isInstantApp = isInstantApp(packageName, userId);
14958                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14959                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14960                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14961            }
14962        });
14963    }
14964
14965    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14966            int[] userIds, int[] instantUserIds) {
14967        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14968                installerPkg, null, userIds, instantUserIds);
14969    }
14970
14971    private abstract class HandlerParams {
14972        private static final int MAX_RETRIES = 4;
14973
14974        /**
14975         * Number of times startCopy() has been attempted and had a non-fatal
14976         * error.
14977         */
14978        private int mRetries = 0;
14979
14980        /** User handle for the user requesting the information or installation. */
14981        private final UserHandle mUser;
14982        String traceMethod;
14983        int traceCookie;
14984
14985        HandlerParams(UserHandle user) {
14986            mUser = user;
14987        }
14988
14989        UserHandle getUser() {
14990            return mUser;
14991        }
14992
14993        HandlerParams setTraceMethod(String traceMethod) {
14994            this.traceMethod = traceMethod;
14995            return this;
14996        }
14997
14998        HandlerParams setTraceCookie(int traceCookie) {
14999            this.traceCookie = traceCookie;
15000            return this;
15001        }
15002
15003        final boolean startCopy() {
15004            boolean res;
15005            try {
15006                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15007
15008                if (++mRetries > MAX_RETRIES) {
15009                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15010                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15011                    handleServiceError();
15012                    return false;
15013                } else {
15014                    handleStartCopy();
15015                    res = true;
15016                }
15017            } catch (RemoteException e) {
15018                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15019                mHandler.sendEmptyMessage(MCS_RECONNECT);
15020                res = false;
15021            }
15022            handleReturnCode();
15023            return res;
15024        }
15025
15026        final void serviceError() {
15027            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15028            handleServiceError();
15029            handleReturnCode();
15030        }
15031
15032        abstract void handleStartCopy() throws RemoteException;
15033        abstract void handleServiceError();
15034        abstract void handleReturnCode();
15035    }
15036
15037    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15038        for (File path : paths) {
15039            try {
15040                mcs.clearDirectory(path.getAbsolutePath());
15041            } catch (RemoteException e) {
15042            }
15043        }
15044    }
15045
15046    static class OriginInfo {
15047        /**
15048         * Location where install is coming from, before it has been
15049         * copied/renamed into place. This could be a single monolithic APK
15050         * file, or a cluster directory. This location may be untrusted.
15051         */
15052        final File file;
15053
15054        /**
15055         * Flag indicating that {@link #file} or {@link #cid} has already been
15056         * staged, meaning downstream users don't need to defensively copy the
15057         * contents.
15058         */
15059        final boolean staged;
15060
15061        /**
15062         * Flag indicating that {@link #file} or {@link #cid} is an already
15063         * installed app that is being moved.
15064         */
15065        final boolean existing;
15066
15067        final String resolvedPath;
15068        final File resolvedFile;
15069
15070        static OriginInfo fromNothing() {
15071            return new OriginInfo(null, false, false);
15072        }
15073
15074        static OriginInfo fromUntrustedFile(File file) {
15075            return new OriginInfo(file, false, false);
15076        }
15077
15078        static OriginInfo fromExistingFile(File file) {
15079            return new OriginInfo(file, false, true);
15080        }
15081
15082        static OriginInfo fromStagedFile(File file) {
15083            return new OriginInfo(file, true, false);
15084        }
15085
15086        private OriginInfo(File file, boolean staged, boolean existing) {
15087            this.file = file;
15088            this.staged = staged;
15089            this.existing = existing;
15090
15091            if (file != null) {
15092                resolvedPath = file.getAbsolutePath();
15093                resolvedFile = file;
15094            } else {
15095                resolvedPath = null;
15096                resolvedFile = null;
15097            }
15098        }
15099    }
15100
15101    static class MoveInfo {
15102        final int moveId;
15103        final String fromUuid;
15104        final String toUuid;
15105        final String packageName;
15106        final String dataAppName;
15107        final int appId;
15108        final String seinfo;
15109        final int targetSdkVersion;
15110
15111        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15112                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15113            this.moveId = moveId;
15114            this.fromUuid = fromUuid;
15115            this.toUuid = toUuid;
15116            this.packageName = packageName;
15117            this.dataAppName = dataAppName;
15118            this.appId = appId;
15119            this.seinfo = seinfo;
15120            this.targetSdkVersion = targetSdkVersion;
15121        }
15122    }
15123
15124    static class VerificationInfo {
15125        /** A constant used to indicate that a uid value is not present. */
15126        public static final int NO_UID = -1;
15127
15128        /** URI referencing where the package was downloaded from. */
15129        final Uri originatingUri;
15130
15131        /** HTTP referrer URI associated with the originatingURI. */
15132        final Uri referrer;
15133
15134        /** UID of the application that the install request originated from. */
15135        final int originatingUid;
15136
15137        /** UID of application requesting the install */
15138        final int installerUid;
15139
15140        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15141            this.originatingUri = originatingUri;
15142            this.referrer = referrer;
15143            this.originatingUid = originatingUid;
15144            this.installerUid = installerUid;
15145        }
15146    }
15147
15148    class InstallParams extends HandlerParams {
15149        final OriginInfo origin;
15150        final MoveInfo move;
15151        final IPackageInstallObserver2 observer;
15152        int installFlags;
15153        final String installerPackageName;
15154        final String volumeUuid;
15155        private InstallArgs mArgs;
15156        private int mRet;
15157        final String packageAbiOverride;
15158        final String[] grantedRuntimePermissions;
15159        final VerificationInfo verificationInfo;
15160        final PackageParser.SigningDetails signingDetails;
15161        final int installReason;
15162
15163        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15164                int installFlags, String installerPackageName, String volumeUuid,
15165                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15166                String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
15167            super(user);
15168            this.origin = origin;
15169            this.move = move;
15170            this.observer = observer;
15171            this.installFlags = installFlags;
15172            this.installerPackageName = installerPackageName;
15173            this.volumeUuid = volumeUuid;
15174            this.verificationInfo = verificationInfo;
15175            this.packageAbiOverride = packageAbiOverride;
15176            this.grantedRuntimePermissions = grantedPermissions;
15177            this.signingDetails = signingDetails;
15178            this.installReason = installReason;
15179        }
15180
15181        @Override
15182        public String toString() {
15183            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15184                    + " file=" + origin.file + "}";
15185        }
15186
15187        private int installLocationPolicy(PackageInfoLite pkgLite) {
15188            String packageName = pkgLite.packageName;
15189            int installLocation = pkgLite.installLocation;
15190            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15191            // reader
15192            synchronized (mPackages) {
15193                // Currently installed package which the new package is attempting to replace or
15194                // null if no such package is installed.
15195                PackageParser.Package installedPkg = mPackages.get(packageName);
15196                // Package which currently owns the data which the new package will own if installed.
15197                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15198                // will be null whereas dataOwnerPkg will contain information about the package
15199                // which was uninstalled while keeping its data.
15200                PackageParser.Package dataOwnerPkg = installedPkg;
15201                if (dataOwnerPkg  == null) {
15202                    PackageSetting ps = mSettings.mPackages.get(packageName);
15203                    if (ps != null) {
15204                        dataOwnerPkg = ps.pkg;
15205                    }
15206                }
15207
15208                if (dataOwnerPkg != null) {
15209                    // If installed, the package will get access to data left on the device by its
15210                    // predecessor. As a security measure, this is permited only if this is not a
15211                    // version downgrade or if the predecessor package is marked as debuggable and
15212                    // a downgrade is explicitly requested.
15213                    //
15214                    // On debuggable platform builds, downgrades are permitted even for
15215                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15216                    // not offer security guarantees and thus it's OK to disable some security
15217                    // mechanisms to make debugging/testing easier on those builds. However, even on
15218                    // debuggable builds downgrades of packages are permitted only if requested via
15219                    // installFlags. This is because we aim to keep the behavior of debuggable
15220                    // platform builds as close as possible to the behavior of non-debuggable
15221                    // platform builds.
15222                    final boolean downgradeRequested =
15223                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15224                    final boolean packageDebuggable =
15225                                (dataOwnerPkg.applicationInfo.flags
15226                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15227                    final boolean downgradePermitted =
15228                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15229                    if (!downgradePermitted) {
15230                        try {
15231                            checkDowngrade(dataOwnerPkg, pkgLite);
15232                        } catch (PackageManagerException e) {
15233                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15234                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15235                        }
15236                    }
15237                }
15238
15239                if (installedPkg != null) {
15240                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15241                        // Check for updated system application.
15242                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15243                            if (onSd) {
15244                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15245                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15246                            }
15247                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15248                        } else {
15249                            if (onSd) {
15250                                // Install flag overrides everything.
15251                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15252                            }
15253                            // If current upgrade specifies particular preference
15254                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15255                                // Application explicitly specified internal.
15256                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15257                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15258                                // App explictly prefers external. Let policy decide
15259                            } else {
15260                                // Prefer previous location
15261                                if (isExternal(installedPkg)) {
15262                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15263                                }
15264                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15265                            }
15266                        }
15267                    } else {
15268                        // Invalid install. Return error code
15269                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15270                    }
15271                }
15272            }
15273            // All the special cases have been taken care of.
15274            // Return result based on recommended install location.
15275            if (onSd) {
15276                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15277            }
15278            return pkgLite.recommendedInstallLocation;
15279        }
15280
15281        /*
15282         * Invoke remote method to get package information and install
15283         * location values. Override install location based on default
15284         * policy if needed and then create install arguments based
15285         * on the install location.
15286         */
15287        public void handleStartCopy() throws RemoteException {
15288            int ret = PackageManager.INSTALL_SUCCEEDED;
15289
15290            // If we're already staged, we've firmly committed to an install location
15291            if (origin.staged) {
15292                if (origin.file != null) {
15293                    installFlags |= PackageManager.INSTALL_INTERNAL;
15294                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15295                } else {
15296                    throw new IllegalStateException("Invalid stage location");
15297                }
15298            }
15299
15300            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15301            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15302            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15303            PackageInfoLite pkgLite = null;
15304
15305            if (onInt && onSd) {
15306                // Check if both bits are set.
15307                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15308                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15309            } else if (onSd && ephemeral) {
15310                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15311                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15312            } else {
15313                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15314                        packageAbiOverride);
15315
15316                if (DEBUG_INSTANT && ephemeral) {
15317                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15318                }
15319
15320                /*
15321                 * If we have too little free space, try to free cache
15322                 * before giving up.
15323                 */
15324                if (!origin.staged && pkgLite.recommendedInstallLocation
15325                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15326                    // TODO: focus freeing disk space on the target device
15327                    final StorageManager storage = StorageManager.from(mContext);
15328                    final long lowThreshold = storage.getStorageLowBytes(
15329                            Environment.getDataDirectory());
15330
15331                    final long sizeBytes = mContainerService.calculateInstalledSize(
15332                            origin.resolvedPath, packageAbiOverride);
15333
15334                    try {
15335                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15336                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15337                                installFlags, packageAbiOverride);
15338                    } catch (InstallerException e) {
15339                        Slog.w(TAG, "Failed to free cache", e);
15340                    }
15341
15342                    /*
15343                     * The cache free must have deleted the file we
15344                     * downloaded to install.
15345                     *
15346                     * TODO: fix the "freeCache" call to not delete
15347                     *       the file we care about.
15348                     */
15349                    if (pkgLite.recommendedInstallLocation
15350                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15351                        pkgLite.recommendedInstallLocation
15352                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15353                    }
15354                }
15355            }
15356
15357            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15358                int loc = pkgLite.recommendedInstallLocation;
15359                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15360                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15361                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15362                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15363                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15364                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15365                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15366                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15367                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15368                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15369                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15370                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15371                } else {
15372                    // Override with defaults if needed.
15373                    loc = installLocationPolicy(pkgLite);
15374                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15375                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15376                    } else if (!onSd && !onInt) {
15377                        // Override install location with flags
15378                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15379                            // Set the flag to install on external media.
15380                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15381                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15382                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15383                            if (DEBUG_INSTANT) {
15384                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15385                            }
15386                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15387                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15388                                    |PackageManager.INSTALL_INTERNAL);
15389                        } else {
15390                            // Make sure the flag for installing on external
15391                            // media is unset
15392                            installFlags |= PackageManager.INSTALL_INTERNAL;
15393                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15394                        }
15395                    }
15396                }
15397            }
15398
15399            final InstallArgs args = createInstallArgs(this);
15400            mArgs = args;
15401
15402            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15403                // TODO: http://b/22976637
15404                // Apps installed for "all" users use the device owner to verify the app
15405                UserHandle verifierUser = getUser();
15406                if (verifierUser == UserHandle.ALL) {
15407                    verifierUser = UserHandle.SYSTEM;
15408                }
15409
15410                /*
15411                 * Determine if we have any installed package verifiers. If we
15412                 * do, then we'll defer to them to verify the packages.
15413                 */
15414                final int requiredUid = mRequiredVerifierPackage == null ? -1
15415                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15416                                verifierUser.getIdentifier());
15417                final int installerUid =
15418                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15419                if (!origin.existing && requiredUid != -1
15420                        && isVerificationEnabled(
15421                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15422                    final Intent verification = new Intent(
15423                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15424                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15425                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15426                            PACKAGE_MIME_TYPE);
15427                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15428
15429                    // Query all live verifiers based on current user state
15430                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15431                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15432                            false /*allowDynamicSplits*/);
15433
15434                    if (DEBUG_VERIFY) {
15435                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15436                                + verification.toString() + " with " + pkgLite.verifiers.length
15437                                + " optional verifiers");
15438                    }
15439
15440                    final int verificationId = mPendingVerificationToken++;
15441
15442                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15443
15444                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15445                            installerPackageName);
15446
15447                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15448                            installFlags);
15449
15450                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15451                            pkgLite.packageName);
15452
15453                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15454                            pkgLite.versionCode);
15455
15456                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
15457                            pkgLite.getLongVersionCode());
15458
15459                    if (verificationInfo != null) {
15460                        if (verificationInfo.originatingUri != null) {
15461                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15462                                    verificationInfo.originatingUri);
15463                        }
15464                        if (verificationInfo.referrer != null) {
15465                            verification.putExtra(Intent.EXTRA_REFERRER,
15466                                    verificationInfo.referrer);
15467                        }
15468                        if (verificationInfo.originatingUid >= 0) {
15469                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15470                                    verificationInfo.originatingUid);
15471                        }
15472                        if (verificationInfo.installerUid >= 0) {
15473                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15474                                    verificationInfo.installerUid);
15475                        }
15476                    }
15477
15478                    final PackageVerificationState verificationState = new PackageVerificationState(
15479                            requiredUid, args);
15480
15481                    mPendingVerification.append(verificationId, verificationState);
15482
15483                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15484                            receivers, verificationState);
15485
15486                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15487                    final long idleDuration = getVerificationTimeout();
15488
15489                    /*
15490                     * If any sufficient verifiers were listed in the package
15491                     * manifest, attempt to ask them.
15492                     */
15493                    if (sufficientVerifiers != null) {
15494                        final int N = sufficientVerifiers.size();
15495                        if (N == 0) {
15496                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15497                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15498                        } else {
15499                            for (int i = 0; i < N; i++) {
15500                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15501                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15502                                        verifierComponent.getPackageName(), idleDuration,
15503                                        verifierUser.getIdentifier(), false, "package verifier");
15504
15505                                final Intent sufficientIntent = new Intent(verification);
15506                                sufficientIntent.setComponent(verifierComponent);
15507                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15508                            }
15509                        }
15510                    }
15511
15512                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15513                            mRequiredVerifierPackage, receivers);
15514                    if (ret == PackageManager.INSTALL_SUCCEEDED
15515                            && mRequiredVerifierPackage != null) {
15516                        Trace.asyncTraceBegin(
15517                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15518                        /*
15519                         * Send the intent to the required verification agent,
15520                         * but only start the verification timeout after the
15521                         * target BroadcastReceivers have run.
15522                         */
15523                        verification.setComponent(requiredVerifierComponent);
15524                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15525                                mRequiredVerifierPackage, idleDuration,
15526                                verifierUser.getIdentifier(), false, "package verifier");
15527                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15528                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15529                                new BroadcastReceiver() {
15530                                    @Override
15531                                    public void onReceive(Context context, Intent intent) {
15532                                        final Message msg = mHandler
15533                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15534                                        msg.arg1 = verificationId;
15535                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15536                                    }
15537                                }, null, 0, null, null);
15538
15539                        /*
15540                         * We don't want the copy to proceed until verification
15541                         * succeeds, so null out this field.
15542                         */
15543                        mArgs = null;
15544                    }
15545                } else {
15546                    /*
15547                     * No package verification is enabled, so immediately start
15548                     * the remote call to initiate copy using temporary file.
15549                     */
15550                    ret = args.copyApk(mContainerService, true);
15551                }
15552            }
15553
15554            mRet = ret;
15555        }
15556
15557        @Override
15558        void handleReturnCode() {
15559            // If mArgs is null, then MCS couldn't be reached. When it
15560            // reconnects, it will try again to install. At that point, this
15561            // will succeed.
15562            if (mArgs != null) {
15563                processPendingInstall(mArgs, mRet);
15564            }
15565        }
15566
15567        @Override
15568        void handleServiceError() {
15569            mArgs = createInstallArgs(this);
15570            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15571        }
15572    }
15573
15574    private InstallArgs createInstallArgs(InstallParams params) {
15575        if (params.move != null) {
15576            return new MoveInstallArgs(params);
15577        } else {
15578            return new FileInstallArgs(params);
15579        }
15580    }
15581
15582    /**
15583     * Create args that describe an existing installed package. Typically used
15584     * when cleaning up old installs, or used as a move source.
15585     */
15586    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15587            String resourcePath, String[] instructionSets) {
15588        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15589    }
15590
15591    static abstract class InstallArgs {
15592        /** @see InstallParams#origin */
15593        final OriginInfo origin;
15594        /** @see InstallParams#move */
15595        final MoveInfo move;
15596
15597        final IPackageInstallObserver2 observer;
15598        // Always refers to PackageManager flags only
15599        final int installFlags;
15600        final String installerPackageName;
15601        final String volumeUuid;
15602        final UserHandle user;
15603        final String abiOverride;
15604        final String[] installGrantPermissions;
15605        /** If non-null, drop an async trace when the install completes */
15606        final String traceMethod;
15607        final int traceCookie;
15608        final PackageParser.SigningDetails signingDetails;
15609        final int installReason;
15610
15611        // The list of instruction sets supported by this app. This is currently
15612        // only used during the rmdex() phase to clean up resources. We can get rid of this
15613        // if we move dex files under the common app path.
15614        /* nullable */ String[] instructionSets;
15615
15616        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15617                int installFlags, String installerPackageName, String volumeUuid,
15618                UserHandle user, String[] instructionSets,
15619                String abiOverride, String[] installGrantPermissions,
15620                String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
15621                int installReason) {
15622            this.origin = origin;
15623            this.move = move;
15624            this.installFlags = installFlags;
15625            this.observer = observer;
15626            this.installerPackageName = installerPackageName;
15627            this.volumeUuid = volumeUuid;
15628            this.user = user;
15629            this.instructionSets = instructionSets;
15630            this.abiOverride = abiOverride;
15631            this.installGrantPermissions = installGrantPermissions;
15632            this.traceMethod = traceMethod;
15633            this.traceCookie = traceCookie;
15634            this.signingDetails = signingDetails;
15635            this.installReason = installReason;
15636        }
15637
15638        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15639        abstract int doPreInstall(int status);
15640
15641        /**
15642         * Rename package into final resting place. All paths on the given
15643         * scanned package should be updated to reflect the rename.
15644         */
15645        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15646        abstract int doPostInstall(int status, int uid);
15647
15648        /** @see PackageSettingBase#codePathString */
15649        abstract String getCodePath();
15650        /** @see PackageSettingBase#resourcePathString */
15651        abstract String getResourcePath();
15652
15653        // Need installer lock especially for dex file removal.
15654        abstract void cleanUpResourcesLI();
15655        abstract boolean doPostDeleteLI(boolean delete);
15656
15657        /**
15658         * Called before the source arguments are copied. This is used mostly
15659         * for MoveParams when it needs to read the source file to put it in the
15660         * destination.
15661         */
15662        int doPreCopy() {
15663            return PackageManager.INSTALL_SUCCEEDED;
15664        }
15665
15666        /**
15667         * Called after the source arguments are copied. This is used mostly for
15668         * MoveParams when it needs to read the source file to put it in the
15669         * destination.
15670         */
15671        int doPostCopy(int uid) {
15672            return PackageManager.INSTALL_SUCCEEDED;
15673        }
15674
15675        protected boolean isFwdLocked() {
15676            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15677        }
15678
15679        protected boolean isExternalAsec() {
15680            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15681        }
15682
15683        protected boolean isEphemeral() {
15684            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15685        }
15686
15687        UserHandle getUser() {
15688            return user;
15689        }
15690    }
15691
15692    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15693        if (!allCodePaths.isEmpty()) {
15694            if (instructionSets == null) {
15695                throw new IllegalStateException("instructionSet == null");
15696            }
15697            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15698            for (String codePath : allCodePaths) {
15699                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15700                    try {
15701                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15702                    } catch (InstallerException ignored) {
15703                    }
15704                }
15705            }
15706        }
15707    }
15708
15709    /**
15710     * Logic to handle installation of non-ASEC applications, including copying
15711     * and renaming logic.
15712     */
15713    class FileInstallArgs extends InstallArgs {
15714        private File codeFile;
15715        private File resourceFile;
15716
15717        // Example topology:
15718        // /data/app/com.example/base.apk
15719        // /data/app/com.example/split_foo.apk
15720        // /data/app/com.example/lib/arm/libfoo.so
15721        // /data/app/com.example/lib/arm64/libfoo.so
15722        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15723
15724        /** New install */
15725        FileInstallArgs(InstallParams params) {
15726            super(params.origin, params.move, params.observer, params.installFlags,
15727                    params.installerPackageName, params.volumeUuid,
15728                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15729                    params.grantedRuntimePermissions,
15730                    params.traceMethod, params.traceCookie, params.signingDetails,
15731                    params.installReason);
15732            if (isFwdLocked()) {
15733                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15734            }
15735        }
15736
15737        /** Existing install */
15738        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15739            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15740                    null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15741                    PackageManager.INSTALL_REASON_UNKNOWN);
15742            this.codeFile = (codePath != null) ? new File(codePath) : null;
15743            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15744        }
15745
15746        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15747            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15748            try {
15749                return doCopyApk(imcs, temp);
15750            } finally {
15751                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15752            }
15753        }
15754
15755        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15756            if (origin.staged) {
15757                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15758                codeFile = origin.file;
15759                resourceFile = origin.file;
15760                return PackageManager.INSTALL_SUCCEEDED;
15761            }
15762
15763            try {
15764                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15765                final File tempDir =
15766                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15767                codeFile = tempDir;
15768                resourceFile = tempDir;
15769            } catch (IOException e) {
15770                Slog.w(TAG, "Failed to create copy file: " + e);
15771                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15772            }
15773
15774            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15775                @Override
15776                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15777                    if (!FileUtils.isValidExtFilename(name)) {
15778                        throw new IllegalArgumentException("Invalid filename: " + name);
15779                    }
15780                    try {
15781                        final File file = new File(codeFile, name);
15782                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15783                                O_RDWR | O_CREAT, 0644);
15784                        Os.chmod(file.getAbsolutePath(), 0644);
15785                        return new ParcelFileDescriptor(fd);
15786                    } catch (ErrnoException e) {
15787                        throw new RemoteException("Failed to open: " + e.getMessage());
15788                    }
15789                }
15790            };
15791
15792            int ret = PackageManager.INSTALL_SUCCEEDED;
15793            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15794            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15795                Slog.e(TAG, "Failed to copy package");
15796                return ret;
15797            }
15798
15799            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15800            NativeLibraryHelper.Handle handle = null;
15801            try {
15802                handle = NativeLibraryHelper.Handle.create(codeFile);
15803                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15804                        abiOverride);
15805            } catch (IOException e) {
15806                Slog.e(TAG, "Copying native libraries failed", e);
15807                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15808            } finally {
15809                IoUtils.closeQuietly(handle);
15810            }
15811
15812            return ret;
15813        }
15814
15815        int doPreInstall(int status) {
15816            if (status != PackageManager.INSTALL_SUCCEEDED) {
15817                cleanUp();
15818            }
15819            return status;
15820        }
15821
15822        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15823            if (status != PackageManager.INSTALL_SUCCEEDED) {
15824                cleanUp();
15825                return false;
15826            }
15827
15828            final File targetDir = codeFile.getParentFile();
15829            final File beforeCodeFile = codeFile;
15830            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15831
15832            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15833            try {
15834                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15835            } catch (ErrnoException e) {
15836                Slog.w(TAG, "Failed to rename", e);
15837                return false;
15838            }
15839
15840            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15841                Slog.w(TAG, "Failed to restorecon");
15842                return false;
15843            }
15844
15845            // Reflect the rename internally
15846            codeFile = afterCodeFile;
15847            resourceFile = afterCodeFile;
15848
15849            // Reflect the rename in scanned details
15850            try {
15851                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15852            } catch (IOException e) {
15853                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15854                return false;
15855            }
15856            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15857                    afterCodeFile, pkg.baseCodePath));
15858            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15859                    afterCodeFile, pkg.splitCodePaths));
15860
15861            // Reflect the rename in app info
15862            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15863            pkg.setApplicationInfoCodePath(pkg.codePath);
15864            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15865            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15866            pkg.setApplicationInfoResourcePath(pkg.codePath);
15867            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15868            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15869
15870            return true;
15871        }
15872
15873        int doPostInstall(int status, int uid) {
15874            if (status != PackageManager.INSTALL_SUCCEEDED) {
15875                cleanUp();
15876            }
15877            return status;
15878        }
15879
15880        @Override
15881        String getCodePath() {
15882            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15883        }
15884
15885        @Override
15886        String getResourcePath() {
15887            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15888        }
15889
15890        private boolean cleanUp() {
15891            if (codeFile == null || !codeFile.exists()) {
15892                return false;
15893            }
15894
15895            removeCodePathLI(codeFile);
15896
15897            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15898                resourceFile.delete();
15899            }
15900
15901            return true;
15902        }
15903
15904        void cleanUpResourcesLI() {
15905            // Try enumerating all code paths before deleting
15906            List<String> allCodePaths = Collections.EMPTY_LIST;
15907            if (codeFile != null && codeFile.exists()) {
15908                try {
15909                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15910                    allCodePaths = pkg.getAllCodePaths();
15911                } catch (PackageParserException e) {
15912                    // Ignored; we tried our best
15913                }
15914            }
15915
15916            cleanUp();
15917            removeDexFiles(allCodePaths, instructionSets);
15918        }
15919
15920        boolean doPostDeleteLI(boolean delete) {
15921            // XXX err, shouldn't we respect the delete flag?
15922            cleanUpResourcesLI();
15923            return true;
15924        }
15925    }
15926
15927    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15928            PackageManagerException {
15929        if (copyRet < 0) {
15930            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15931                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15932                throw new PackageManagerException(copyRet, message);
15933            }
15934        }
15935    }
15936
15937    /**
15938     * Extract the StorageManagerService "container ID" from the full code path of an
15939     * .apk.
15940     */
15941    static String cidFromCodePath(String fullCodePath) {
15942        int eidx = fullCodePath.lastIndexOf("/");
15943        String subStr1 = fullCodePath.substring(0, eidx);
15944        int sidx = subStr1.lastIndexOf("/");
15945        return subStr1.substring(sidx+1, eidx);
15946    }
15947
15948    /**
15949     * Logic to handle movement of existing installed applications.
15950     */
15951    class MoveInstallArgs extends InstallArgs {
15952        private File codeFile;
15953        private File resourceFile;
15954
15955        /** New install */
15956        MoveInstallArgs(InstallParams params) {
15957            super(params.origin, params.move, params.observer, params.installFlags,
15958                    params.installerPackageName, params.volumeUuid,
15959                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15960                    params.grantedRuntimePermissions,
15961                    params.traceMethod, params.traceCookie, params.signingDetails,
15962                    params.installReason);
15963        }
15964
15965        int copyApk(IMediaContainerService imcs, boolean temp) {
15966            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15967                    + move.fromUuid + " to " + move.toUuid);
15968            synchronized (mInstaller) {
15969                try {
15970                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15971                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15972                } catch (InstallerException e) {
15973                    Slog.w(TAG, "Failed to move app", e);
15974                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15975                }
15976            }
15977
15978            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15979            resourceFile = codeFile;
15980            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15981
15982            return PackageManager.INSTALL_SUCCEEDED;
15983        }
15984
15985        int doPreInstall(int status) {
15986            if (status != PackageManager.INSTALL_SUCCEEDED) {
15987                cleanUp(move.toUuid);
15988            }
15989            return status;
15990        }
15991
15992        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15993            if (status != PackageManager.INSTALL_SUCCEEDED) {
15994                cleanUp(move.toUuid);
15995                return false;
15996            }
15997
15998            // Reflect the move in app info
15999            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16000            pkg.setApplicationInfoCodePath(pkg.codePath);
16001            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16002            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16003            pkg.setApplicationInfoResourcePath(pkg.codePath);
16004            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16005            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16006
16007            return true;
16008        }
16009
16010        int doPostInstall(int status, int uid) {
16011            if (status == PackageManager.INSTALL_SUCCEEDED) {
16012                cleanUp(move.fromUuid);
16013            } else {
16014                cleanUp(move.toUuid);
16015            }
16016            return status;
16017        }
16018
16019        @Override
16020        String getCodePath() {
16021            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16022        }
16023
16024        @Override
16025        String getResourcePath() {
16026            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16027        }
16028
16029        private boolean cleanUp(String volumeUuid) {
16030            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16031                    move.dataAppName);
16032            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16033            final int[] userIds = sUserManager.getUserIds();
16034            synchronized (mInstallLock) {
16035                // Clean up both app data and code
16036                // All package moves are frozen until finished
16037                for (int userId : userIds) {
16038                    try {
16039                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16040                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16041                    } catch (InstallerException e) {
16042                        Slog.w(TAG, String.valueOf(e));
16043                    }
16044                }
16045                removeCodePathLI(codeFile);
16046            }
16047            return true;
16048        }
16049
16050        void cleanUpResourcesLI() {
16051            throw new UnsupportedOperationException();
16052        }
16053
16054        boolean doPostDeleteLI(boolean delete) {
16055            throw new UnsupportedOperationException();
16056        }
16057    }
16058
16059    static String getAsecPackageName(String packageCid) {
16060        int idx = packageCid.lastIndexOf("-");
16061        if (idx == -1) {
16062            return packageCid;
16063        }
16064        return packageCid.substring(0, idx);
16065    }
16066
16067    // Utility method used to create code paths based on package name and available index.
16068    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16069        String idxStr = "";
16070        int idx = 1;
16071        // Fall back to default value of idx=1 if prefix is not
16072        // part of oldCodePath
16073        if (oldCodePath != null) {
16074            String subStr = oldCodePath;
16075            // Drop the suffix right away
16076            if (suffix != null && subStr.endsWith(suffix)) {
16077                subStr = subStr.substring(0, subStr.length() - suffix.length());
16078            }
16079            // If oldCodePath already contains prefix find out the
16080            // ending index to either increment or decrement.
16081            int sidx = subStr.lastIndexOf(prefix);
16082            if (sidx != -1) {
16083                subStr = subStr.substring(sidx + prefix.length());
16084                if (subStr != null) {
16085                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16086                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16087                    }
16088                    try {
16089                        idx = Integer.parseInt(subStr);
16090                        if (idx <= 1) {
16091                            idx++;
16092                        } else {
16093                            idx--;
16094                        }
16095                    } catch(NumberFormatException e) {
16096                    }
16097                }
16098            }
16099        }
16100        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16101        return prefix + idxStr;
16102    }
16103
16104    private File getNextCodePath(File targetDir, String packageName) {
16105        File result;
16106        SecureRandom random = new SecureRandom();
16107        byte[] bytes = new byte[16];
16108        do {
16109            random.nextBytes(bytes);
16110            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16111            result = new File(targetDir, packageName + "-" + suffix);
16112        } while (result.exists());
16113        return result;
16114    }
16115
16116    // Utility method that returns the relative package path with respect
16117    // to the installation directory. Like say for /data/data/com.test-1.apk
16118    // string com.test-1 is returned.
16119    static String deriveCodePathName(String codePath) {
16120        if (codePath == null) {
16121            return null;
16122        }
16123        final File codeFile = new File(codePath);
16124        final String name = codeFile.getName();
16125        if (codeFile.isDirectory()) {
16126            return name;
16127        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16128            final int lastDot = name.lastIndexOf('.');
16129            return name.substring(0, lastDot);
16130        } else {
16131            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16132            return null;
16133        }
16134    }
16135
16136    static class PackageInstalledInfo {
16137        String name;
16138        int uid;
16139        // The set of users that originally had this package installed.
16140        int[] origUsers;
16141        // The set of users that now have this package installed.
16142        int[] newUsers;
16143        PackageParser.Package pkg;
16144        int returnCode;
16145        String returnMsg;
16146        String installerPackageName;
16147        PackageRemovedInfo removedInfo;
16148        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16149
16150        public void setError(int code, String msg) {
16151            setReturnCode(code);
16152            setReturnMessage(msg);
16153            Slog.w(TAG, msg);
16154        }
16155
16156        public void setError(String msg, PackageParserException e) {
16157            setReturnCode(e.error);
16158            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16159            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16160            for (int i = 0; i < childCount; i++) {
16161                addedChildPackages.valueAt(i).setError(msg, e);
16162            }
16163            Slog.w(TAG, msg, e);
16164        }
16165
16166        public void setError(String msg, PackageManagerException e) {
16167            returnCode = e.error;
16168            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16169            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16170            for (int i = 0; i < childCount; i++) {
16171                addedChildPackages.valueAt(i).setError(msg, e);
16172            }
16173            Slog.w(TAG, msg, e);
16174        }
16175
16176        public void setReturnCode(int returnCode) {
16177            this.returnCode = returnCode;
16178            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16179            for (int i = 0; i < childCount; i++) {
16180                addedChildPackages.valueAt(i).returnCode = returnCode;
16181            }
16182        }
16183
16184        private void setReturnMessage(String returnMsg) {
16185            this.returnMsg = returnMsg;
16186            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16187            for (int i = 0; i < childCount; i++) {
16188                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16189            }
16190        }
16191
16192        // In some error cases we want to convey more info back to the observer
16193        String origPackage;
16194        String origPermission;
16195    }
16196
16197    /*
16198     * Install a non-existing package.
16199     */
16200    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16201            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16202            String volumeUuid, PackageInstalledInfo res, int installReason) {
16203        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16204
16205        // Remember this for later, in case we need to rollback this install
16206        String pkgName = pkg.packageName;
16207
16208        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16209
16210        synchronized(mPackages) {
16211            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16212            if (renamedPackage != null) {
16213                // A package with the same name is already installed, though
16214                // it has been renamed to an older name.  The package we
16215                // are trying to install should be installed as an update to
16216                // the existing one, but that has not been requested, so bail.
16217                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16218                        + " without first uninstalling package running as "
16219                        + renamedPackage);
16220                return;
16221            }
16222            if (mPackages.containsKey(pkgName)) {
16223                // Don't allow installation over an existing package with the same name.
16224                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16225                        + " without first uninstalling.");
16226                return;
16227            }
16228        }
16229
16230        try {
16231            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
16232                    System.currentTimeMillis(), user);
16233
16234            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16235
16236            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16237                prepareAppDataAfterInstallLIF(newPackage);
16238
16239            } else {
16240                // Remove package from internal structures, but keep around any
16241                // data that might have already existed
16242                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16243                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16244            }
16245        } catch (PackageManagerException e) {
16246            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16247        }
16248
16249        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16250    }
16251
16252    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16253        try (DigestInputStream digestStream =
16254                new DigestInputStream(new FileInputStream(file), digest)) {
16255            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16256        }
16257    }
16258
16259    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16260            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16261            PackageInstalledInfo res, int installReason) {
16262        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16263
16264        final PackageParser.Package oldPackage;
16265        final PackageSetting ps;
16266        final String pkgName = pkg.packageName;
16267        final int[] allUsers;
16268        final int[] installedUsers;
16269
16270        synchronized(mPackages) {
16271            oldPackage = mPackages.get(pkgName);
16272            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16273
16274            // don't allow upgrade to target a release SDK from a pre-release SDK
16275            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16276                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16277            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16278                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16279            if (oldTargetsPreRelease
16280                    && !newTargetsPreRelease
16281                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16282                Slog.w(TAG, "Can't install package targeting released sdk");
16283                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16284                return;
16285            }
16286
16287            ps = mSettings.mPackages.get(pkgName);
16288
16289            // verify signatures are valid
16290            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16291            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
16292                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
16293                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16294                            "New package not signed by keys specified by upgrade-keysets: "
16295                                    + pkgName);
16296                    return;
16297                }
16298            } else {
16299
16300                // default to original signature matching
16301                if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails,
16302                        PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)
16303                                && !oldPackage.mSigningDetails.checkCapability(
16304                                        pkg.mSigningDetails,
16305                                        PackageParser.SigningDetails.CertCapabilities.ROLLBACK)) {
16306                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16307                            "New package has a different signature: " + pkgName);
16308                    return;
16309                }
16310            }
16311
16312            // don't allow a system upgrade unless the upgrade hash matches
16313            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
16314                byte[] digestBytes = null;
16315                try {
16316                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16317                    updateDigest(digest, new File(pkg.baseCodePath));
16318                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16319                        for (String path : pkg.splitCodePaths) {
16320                            updateDigest(digest, new File(path));
16321                        }
16322                    }
16323                    digestBytes = digest.digest();
16324                } catch (NoSuchAlgorithmException | IOException e) {
16325                    res.setError(INSTALL_FAILED_INVALID_APK,
16326                            "Could not compute hash: " + pkgName);
16327                    return;
16328                }
16329                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16330                    res.setError(INSTALL_FAILED_INVALID_APK,
16331                            "New package fails restrict-update check: " + pkgName);
16332                    return;
16333                }
16334                // retain upgrade restriction
16335                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16336            }
16337
16338            // Check for shared user id changes
16339            String invalidPackageName =
16340                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16341            if (invalidPackageName != null) {
16342                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16343                        "Package " + invalidPackageName + " tried to change user "
16344                                + oldPackage.mSharedUserId);
16345                return;
16346            }
16347
16348            // check if the new package supports all of the abis which the old package supports
16349            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
16350            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
16351            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
16352                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16353                        "Update to package " + pkgName + " doesn't support multi arch");
16354                return;
16355            }
16356
16357            // In case of rollback, remember per-user/profile install state
16358            allUsers = sUserManager.getUserIds();
16359            installedUsers = ps.queryInstalledUsers(allUsers, true);
16360
16361            // don't allow an upgrade from full to ephemeral
16362            if (isInstantApp) {
16363                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16364                    for (int currentUser : allUsers) {
16365                        if (!ps.getInstantApp(currentUser)) {
16366                            // can't downgrade from full to instant
16367                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16368                                    + " for user: " + currentUser);
16369                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16370                            return;
16371                        }
16372                    }
16373                } else if (!ps.getInstantApp(user.getIdentifier())) {
16374                    // can't downgrade from full to instant
16375                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16376                            + " for user: " + user.getIdentifier());
16377                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16378                    return;
16379                }
16380            }
16381        }
16382
16383        // Update what is removed
16384        res.removedInfo = new PackageRemovedInfo(this);
16385        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16386        res.removedInfo.removedPackage = oldPackage.packageName;
16387        res.removedInfo.installerPackageName = ps.installerPackageName;
16388        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16389        res.removedInfo.isUpdate = true;
16390        res.removedInfo.origUsers = installedUsers;
16391        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16392        for (int i = 0; i < installedUsers.length; i++) {
16393            final int userId = installedUsers[i];
16394            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16395        }
16396
16397        final int childCount = (oldPackage.childPackages != null)
16398                ? oldPackage.childPackages.size() : 0;
16399        for (int i = 0; i < childCount; i++) {
16400            boolean childPackageUpdated = false;
16401            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16402            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16403            if (res.addedChildPackages != null) {
16404                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16405                if (childRes != null) {
16406                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16407                    childRes.removedInfo.removedPackage = childPkg.packageName;
16408                    if (childPs != null) {
16409                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16410                    }
16411                    childRes.removedInfo.isUpdate = true;
16412                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16413                    childPackageUpdated = true;
16414                }
16415            }
16416            if (!childPackageUpdated) {
16417                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16418                childRemovedRes.removedPackage = childPkg.packageName;
16419                if (childPs != null) {
16420                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16421                }
16422                childRemovedRes.isUpdate = false;
16423                childRemovedRes.dataRemoved = true;
16424                synchronized (mPackages) {
16425                    if (childPs != null) {
16426                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16427                    }
16428                }
16429                if (res.removedInfo.removedChildPackages == null) {
16430                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16431                }
16432                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16433            }
16434        }
16435
16436        boolean sysPkg = (isSystemApp(oldPackage));
16437        if (sysPkg) {
16438            // Set the system/privileged/oem/vendor/product flags as needed
16439            final boolean privileged =
16440                    (oldPackage.applicationInfo.privateFlags
16441                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16442            final boolean oem =
16443                    (oldPackage.applicationInfo.privateFlags
16444                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16445            final boolean vendor =
16446                    (oldPackage.applicationInfo.privateFlags
16447                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
16448            final boolean product =
16449                    (oldPackage.applicationInfo.privateFlags
16450                            & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
16451            final @ParseFlags int systemParseFlags = parseFlags;
16452            final @ScanFlags int systemScanFlags = scanFlags
16453                    | SCAN_AS_SYSTEM
16454                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
16455                    | (oem ? SCAN_AS_OEM : 0)
16456                    | (vendor ? SCAN_AS_VENDOR : 0)
16457                    | (product ? SCAN_AS_PRODUCT : 0);
16458
16459            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
16460                    user, allUsers, installerPackageName, res, installReason);
16461        } else {
16462            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
16463                    user, allUsers, installerPackageName, res, installReason);
16464        }
16465    }
16466
16467    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16468            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16469            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
16470            String installerPackageName, PackageInstalledInfo res, int installReason) {
16471        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16472                + deletedPackage);
16473
16474        String pkgName = deletedPackage.packageName;
16475        boolean deletedPkg = true;
16476        boolean addedPkg = false;
16477        boolean updatedSettings = false;
16478        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16479        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16480                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16481
16482        final long origUpdateTime = (pkg.mExtras != null)
16483                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16484
16485        // First delete the existing package while retaining the data directory
16486        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16487                res.removedInfo, true, pkg)) {
16488            // If the existing package wasn't successfully deleted
16489            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16490            deletedPkg = false;
16491        } else {
16492            // Successfully deleted the old package; proceed with replace.
16493
16494            // If deleted package lived in a container, give users a chance to
16495            // relinquish resources before killing.
16496            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16497                if (DEBUG_INSTALL) {
16498                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16499                }
16500                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16501                final ArrayList<String> pkgList = new ArrayList<String>(1);
16502                pkgList.add(deletedPackage.applicationInfo.packageName);
16503                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16504            }
16505
16506            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16507                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16508
16509            try {
16510                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
16511                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16512                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16513                        installReason);
16514
16515                // Update the in-memory copy of the previous code paths.
16516                PackageSetting ps = mSettings.mPackages.get(pkgName);
16517                if (!killApp) {
16518                    if (ps.oldCodePaths == null) {
16519                        ps.oldCodePaths = new ArraySet<>();
16520                    }
16521                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16522                    if (deletedPackage.splitCodePaths != null) {
16523                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16524                    }
16525                } else {
16526                    ps.oldCodePaths = null;
16527                }
16528                if (ps.childPackageNames != null) {
16529                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16530                        final String childPkgName = ps.childPackageNames.get(i);
16531                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16532                        childPs.oldCodePaths = ps.oldCodePaths;
16533                    }
16534                }
16535                prepareAppDataAfterInstallLIF(newPackage);
16536                addedPkg = true;
16537                mDexManager.notifyPackageUpdated(newPackage.packageName,
16538                        newPackage.baseCodePath, newPackage.splitCodePaths);
16539            } catch (PackageManagerException e) {
16540                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16541            }
16542        }
16543
16544        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16545            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16546
16547            // Revert all internal state mutations and added folders for the failed install
16548            if (addedPkg) {
16549                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16550                        res.removedInfo, true, null);
16551            }
16552
16553            // Restore the old package
16554            if (deletedPkg) {
16555                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16556                File restoreFile = new File(deletedPackage.codePath);
16557                // Parse old package
16558                boolean oldExternal = isExternal(deletedPackage);
16559                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16560                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16561                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16562                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16563                try {
16564                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16565                            null);
16566                } catch (PackageManagerException e) {
16567                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16568                            + e.getMessage());
16569                    return;
16570                }
16571
16572                synchronized (mPackages) {
16573                    // Ensure the installer package name up to date
16574                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16575
16576                    // Update permissions for restored package
16577                    mPermissionManager.updatePermissions(
16578                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16579                            mPermissionCallback);
16580
16581                    mSettings.writeLPr();
16582                }
16583
16584                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16585            }
16586        } else {
16587            synchronized (mPackages) {
16588                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16589                if (ps != null) {
16590                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16591                    if (res.removedInfo.removedChildPackages != null) {
16592                        final int childCount = res.removedInfo.removedChildPackages.size();
16593                        // Iterate in reverse as we may modify the collection
16594                        for (int i = childCount - 1; i >= 0; i--) {
16595                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16596                            if (res.addedChildPackages.containsKey(childPackageName)) {
16597                                res.removedInfo.removedChildPackages.removeAt(i);
16598                            } else {
16599                                PackageRemovedInfo childInfo = res.removedInfo
16600                                        .removedChildPackages.valueAt(i);
16601                                childInfo.removedForAllUsers = mPackages.get(
16602                                        childInfo.removedPackage) == null;
16603                            }
16604                        }
16605                    }
16606                }
16607            }
16608        }
16609    }
16610
16611    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16612            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16613            final @ScanFlags int scanFlags, UserHandle user,
16614            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16615            int installReason) {
16616        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16617                + ", old=" + deletedPackage);
16618
16619        final boolean disabledSystem;
16620
16621        // Remove existing system package
16622        removePackageLI(deletedPackage, true);
16623
16624        synchronized (mPackages) {
16625            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16626        }
16627        if (!disabledSystem) {
16628            // We didn't need to disable the .apk as a current system package,
16629            // which means we are replacing another update that is already
16630            // installed.  We need to make sure to delete the older one's .apk.
16631            res.removedInfo.args = createInstallArgsForExisting(0,
16632                    deletedPackage.applicationInfo.getCodePath(),
16633                    deletedPackage.applicationInfo.getResourcePath(),
16634                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16635        } else {
16636            res.removedInfo.args = null;
16637        }
16638
16639        // Successfully disabled the old package. Now proceed with re-installation
16640        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16641                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16642
16643        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16644        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16645                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16646
16647        PackageParser.Package newPackage = null;
16648        try {
16649            // Add the package to the internal data structures
16650            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16651
16652            // Set the update and install times
16653            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16654            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16655                    System.currentTimeMillis());
16656
16657            // Update the package dynamic state if succeeded
16658            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16659                // Now that the install succeeded make sure we remove data
16660                // directories for any child package the update removed.
16661                final int deletedChildCount = (deletedPackage.childPackages != null)
16662                        ? deletedPackage.childPackages.size() : 0;
16663                final int newChildCount = (newPackage.childPackages != null)
16664                        ? newPackage.childPackages.size() : 0;
16665                for (int i = 0; i < deletedChildCount; i++) {
16666                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16667                    boolean childPackageDeleted = true;
16668                    for (int j = 0; j < newChildCount; j++) {
16669                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16670                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16671                            childPackageDeleted = false;
16672                            break;
16673                        }
16674                    }
16675                    if (childPackageDeleted) {
16676                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16677                                deletedChildPkg.packageName);
16678                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16679                            PackageRemovedInfo removedChildRes = res.removedInfo
16680                                    .removedChildPackages.get(deletedChildPkg.packageName);
16681                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16682                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16683                        }
16684                    }
16685                }
16686
16687                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16688                        installReason);
16689                prepareAppDataAfterInstallLIF(newPackage);
16690
16691                mDexManager.notifyPackageUpdated(newPackage.packageName,
16692                            newPackage.baseCodePath, newPackage.splitCodePaths);
16693            }
16694        } catch (PackageManagerException e) {
16695            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16696            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16697        }
16698
16699        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16700            // Re installation failed. Restore old information
16701            // Remove new pkg information
16702            if (newPackage != null) {
16703                removeInstalledPackageLI(newPackage, true);
16704            }
16705            // Add back the old system package
16706            try {
16707                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16708            } catch (PackageManagerException e) {
16709                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16710            }
16711
16712            synchronized (mPackages) {
16713                if (disabledSystem) {
16714                    enableSystemPackageLPw(deletedPackage);
16715                }
16716
16717                // Ensure the installer package name up to date
16718                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16719
16720                // Update permissions for restored package
16721                mPermissionManager.updatePermissions(
16722                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16723                        mPermissionCallback);
16724
16725                mSettings.writeLPr();
16726            }
16727
16728            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16729                    + " after failed upgrade");
16730        }
16731    }
16732
16733    /**
16734     * Checks whether the parent or any of the child packages have a change shared
16735     * user. For a package to be a valid update the shred users of the parent and
16736     * the children should match. We may later support changing child shared users.
16737     * @param oldPkg The updated package.
16738     * @param newPkg The update package.
16739     * @return The shared user that change between the versions.
16740     */
16741    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16742            PackageParser.Package newPkg) {
16743        // Check parent shared user
16744        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16745            return newPkg.packageName;
16746        }
16747        // Check child shared users
16748        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16749        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16750        for (int i = 0; i < newChildCount; i++) {
16751            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16752            // If this child was present, did it have the same shared user?
16753            for (int j = 0; j < oldChildCount; j++) {
16754                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16755                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16756                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16757                    return newChildPkg.packageName;
16758                }
16759            }
16760        }
16761        return null;
16762    }
16763
16764    private void removeNativeBinariesLI(PackageSetting ps) {
16765        // Remove the lib path for the parent package
16766        if (ps != null) {
16767            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16768            // Remove the lib path for the child packages
16769            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16770            for (int i = 0; i < childCount; i++) {
16771                PackageSetting childPs = null;
16772                synchronized (mPackages) {
16773                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16774                }
16775                if (childPs != null) {
16776                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16777                            .legacyNativeLibraryPathString);
16778                }
16779            }
16780        }
16781    }
16782
16783    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16784        // Enable the parent package
16785        mSettings.enableSystemPackageLPw(pkg.packageName);
16786        // Enable the child packages
16787        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16788        for (int i = 0; i < childCount; i++) {
16789            PackageParser.Package childPkg = pkg.childPackages.get(i);
16790            mSettings.enableSystemPackageLPw(childPkg.packageName);
16791        }
16792    }
16793
16794    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16795            PackageParser.Package newPkg) {
16796        // Disable the parent package (parent always replaced)
16797        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16798        // Disable the child packages
16799        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16800        for (int i = 0; i < childCount; i++) {
16801            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16802            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16803            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16804        }
16805        return disabled;
16806    }
16807
16808    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16809            String installerPackageName) {
16810        // Enable the parent package
16811        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16812        // Enable the child packages
16813        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16814        for (int i = 0; i < childCount; i++) {
16815            PackageParser.Package childPkg = pkg.childPackages.get(i);
16816            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16817        }
16818    }
16819
16820    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16821            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16822        // Update the parent package setting
16823        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16824                res, user, installReason);
16825        // Update the child packages setting
16826        final int childCount = (newPackage.childPackages != null)
16827                ? newPackage.childPackages.size() : 0;
16828        for (int i = 0; i < childCount; i++) {
16829            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16830            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16831            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16832                    childRes.origUsers, childRes, user, installReason);
16833        }
16834    }
16835
16836    private void updateSettingsInternalLI(PackageParser.Package pkg,
16837            String installerPackageName, int[] allUsers, int[] installedForUsers,
16838            PackageInstalledInfo res, UserHandle user, int installReason) {
16839        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16840
16841        final String pkgName = pkg.packageName;
16842
16843        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16844        synchronized (mPackages) {
16845// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16846            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16847                    mPermissionCallback);
16848            // For system-bundled packages, we assume that installing an upgraded version
16849            // of the package implies that the user actually wants to run that new code,
16850            // so we enable the package.
16851            PackageSetting ps = mSettings.mPackages.get(pkgName);
16852            final int userId = user.getIdentifier();
16853            if (ps != null) {
16854                if (isSystemApp(pkg)) {
16855                    if (DEBUG_INSTALL) {
16856                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16857                    }
16858                    // Enable system package for requested users
16859                    if (res.origUsers != null) {
16860                        for (int origUserId : res.origUsers) {
16861                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16862                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16863                                        origUserId, installerPackageName);
16864                            }
16865                        }
16866                    }
16867                    // Also convey the prior install/uninstall state
16868                    if (allUsers != null && installedForUsers != null) {
16869                        for (int currentUserId : allUsers) {
16870                            final boolean installed = ArrayUtils.contains(
16871                                    installedForUsers, currentUserId);
16872                            if (DEBUG_INSTALL) {
16873                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16874                            }
16875                            ps.setInstalled(installed, currentUserId);
16876                        }
16877                        // these install state changes will be persisted in the
16878                        // upcoming call to mSettings.writeLPr().
16879                    }
16880                }
16881                // It's implied that when a user requests installation, they want the app to be
16882                // installed and enabled.
16883                if (userId != UserHandle.USER_ALL) {
16884                    ps.setInstalled(true, userId);
16885                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16886                }
16887
16888                // When replacing an existing package, preserve the original install reason for all
16889                // users that had the package installed before.
16890                final Set<Integer> previousUserIds = new ArraySet<>();
16891                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16892                    final int installReasonCount = res.removedInfo.installReasons.size();
16893                    for (int i = 0; i < installReasonCount; i++) {
16894                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16895                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16896                        ps.setInstallReason(previousInstallReason, previousUserId);
16897                        previousUserIds.add(previousUserId);
16898                    }
16899                }
16900
16901                // Set install reason for users that are having the package newly installed.
16902                if (userId == UserHandle.USER_ALL) {
16903                    for (int currentUserId : sUserManager.getUserIds()) {
16904                        if (!previousUserIds.contains(currentUserId)) {
16905                            ps.setInstallReason(installReason, currentUserId);
16906                        }
16907                    }
16908                } else if (!previousUserIds.contains(userId)) {
16909                    ps.setInstallReason(installReason, userId);
16910                }
16911                mSettings.writeKernelMappingLPr(ps);
16912            }
16913            res.name = pkgName;
16914            res.uid = pkg.applicationInfo.uid;
16915            res.pkg = pkg;
16916            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16917            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16918            //to update install status
16919            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16920            mSettings.writeLPr();
16921            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16922        }
16923
16924        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16925    }
16926
16927    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16928        try {
16929            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16930            installPackageLI(args, res);
16931        } finally {
16932            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16933        }
16934    }
16935
16936    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16937        final int installFlags = args.installFlags;
16938        final String installerPackageName = args.installerPackageName;
16939        final String volumeUuid = args.volumeUuid;
16940        final File tmpPackageFile = new File(args.getCodePath());
16941        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16942        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16943                || (args.volumeUuid != null));
16944        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16945        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16946        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16947        final boolean virtualPreload =
16948                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16949        boolean replace = false;
16950        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16951        if (args.move != null) {
16952            // moving a complete application; perform an initial scan on the new install location
16953            scanFlags |= SCAN_INITIAL;
16954        }
16955        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16956            scanFlags |= SCAN_DONT_KILL_APP;
16957        }
16958        if (instantApp) {
16959            scanFlags |= SCAN_AS_INSTANT_APP;
16960        }
16961        if (fullApp) {
16962            scanFlags |= SCAN_AS_FULL_APP;
16963        }
16964        if (virtualPreload) {
16965            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16966        }
16967
16968        // Result object to be returned
16969        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16970        res.installerPackageName = installerPackageName;
16971
16972        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16973
16974        // Sanity check
16975        if (instantApp && (forwardLocked || onExternal)) {
16976            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16977                    + " external=" + onExternal);
16978            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16979            return;
16980        }
16981
16982        // Retrieve PackageSettings and parse package
16983        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16984                | PackageParser.PARSE_ENFORCE_CODE
16985                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16986                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16987                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16988        PackageParser pp = new PackageParser();
16989        pp.setSeparateProcesses(mSeparateProcesses);
16990        pp.setDisplayMetrics(mMetrics);
16991        pp.setCallback(mPackageParserCallback);
16992
16993        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16994        final PackageParser.Package pkg;
16995        try {
16996            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16997            DexMetadataHelper.validatePackageDexMetadata(pkg);
16998        } catch (PackageParserException e) {
16999            res.setError("Failed parse during installPackageLI", e);
17000            return;
17001        } finally {
17002            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17003        }
17004
17005        // Instant apps have several additional install-time checks.
17006        if (instantApp) {
17007            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
17008                Slog.w(TAG,
17009                        "Instant app package " + pkg.packageName + " does not target at least O");
17010                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17011                        "Instant app package must target at least O");
17012                return;
17013            }
17014            if (pkg.applicationInfo.targetSandboxVersion != 2) {
17015                Slog.w(TAG, "Instant app package " + pkg.packageName
17016                        + " does not target targetSandboxVersion 2");
17017                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17018                        "Instant app package must use targetSandboxVersion 2");
17019                return;
17020            }
17021            if (pkg.mSharedUserId != null) {
17022                Slog.w(TAG, "Instant app package " + pkg.packageName
17023                        + " may not declare sharedUserId.");
17024                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17025                        "Instant app package may not declare a sharedUserId");
17026                return;
17027            }
17028        }
17029
17030        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17031            // Static shared libraries have synthetic package names
17032            renameStaticSharedLibraryPackage(pkg);
17033
17034            // No static shared libs on external storage
17035            if (onExternal) {
17036                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17037                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17038                        "Packages declaring static-shared libs cannot be updated");
17039                return;
17040            }
17041        }
17042
17043        // If we are installing a clustered package add results for the children
17044        if (pkg.childPackages != null) {
17045            synchronized (mPackages) {
17046                final int childCount = pkg.childPackages.size();
17047                for (int i = 0; i < childCount; i++) {
17048                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17049                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17050                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17051                    childRes.pkg = childPkg;
17052                    childRes.name = childPkg.packageName;
17053                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17054                    if (childPs != null) {
17055                        childRes.origUsers = childPs.queryInstalledUsers(
17056                                sUserManager.getUserIds(), true);
17057                    }
17058                    if ((mPackages.containsKey(childPkg.packageName))) {
17059                        childRes.removedInfo = new PackageRemovedInfo(this);
17060                        childRes.removedInfo.removedPackage = childPkg.packageName;
17061                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17062                    }
17063                    if (res.addedChildPackages == null) {
17064                        res.addedChildPackages = new ArrayMap<>();
17065                    }
17066                    res.addedChildPackages.put(childPkg.packageName, childRes);
17067                }
17068            }
17069        }
17070
17071        // If package doesn't declare API override, mark that we have an install
17072        // time CPU ABI override.
17073        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17074            pkg.cpuAbiOverride = args.abiOverride;
17075        }
17076
17077        String pkgName = res.name = pkg.packageName;
17078        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17079            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17080                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17081                return;
17082            }
17083        }
17084
17085        try {
17086            // either use what we've been given or parse directly from the APK
17087            if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
17088                pkg.setSigningDetails(args.signingDetails);
17089            } else {
17090                PackageParser.collectCertificates(pkg, false /* skipVerify */);
17091            }
17092        } catch (PackageParserException e) {
17093            res.setError("Failed collect during installPackageLI", e);
17094            return;
17095        }
17096
17097        if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
17098                < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
17099            Slog.w(TAG, "Instant app package " + pkg.packageName
17100                    + " is not signed with at least APK Signature Scheme v2");
17101            res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17102                    "Instant app package must be signed with APK Signature Scheme v2 or greater");
17103            return;
17104        }
17105
17106        // Get rid of all references to package scan path via parser.
17107        pp = null;
17108        String oldCodePath = null;
17109        boolean systemApp = false;
17110        synchronized (mPackages) {
17111            // Check if installing already existing package
17112            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17113                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17114                if (pkg.mOriginalPackages != null
17115                        && pkg.mOriginalPackages.contains(oldName)
17116                        && mPackages.containsKey(oldName)) {
17117                    // This package is derived from an original package,
17118                    // and this device has been updating from that original
17119                    // name.  We must continue using the original name, so
17120                    // rename the new package here.
17121                    pkg.setPackageName(oldName);
17122                    pkgName = pkg.packageName;
17123                    replace = true;
17124                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17125                            + oldName + " pkgName=" + pkgName);
17126                } else if (mPackages.containsKey(pkgName)) {
17127                    // This package, under its official name, already exists
17128                    // on the device; we should replace it.
17129                    replace = true;
17130                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17131                }
17132
17133                // Child packages are installed through the parent package
17134                if (pkg.parentPackage != null) {
17135                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17136                            "Package " + pkg.packageName + " is child of package "
17137                                    + pkg.parentPackage.parentPackage + ". Child packages "
17138                                    + "can be updated only through the parent package.");
17139                    return;
17140                }
17141
17142                if (replace) {
17143                    // Prevent apps opting out from runtime permissions
17144                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17145                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17146                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17147                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17148                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17149                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17150                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17151                                        + " doesn't support runtime permissions but the old"
17152                                        + " target SDK " + oldTargetSdk + " does.");
17153                        return;
17154                    }
17155                    // Prevent persistent apps from being updated
17156                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
17157                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
17158                                "Package " + oldPackage.packageName + " is a persistent app. "
17159                                        + "Persistent apps are not updateable.");
17160                        return;
17161                    }
17162                    // Prevent apps from downgrading their targetSandbox.
17163                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17164                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17165                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17166                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17167                                "Package " + pkg.packageName + " new target sandbox "
17168                                + newTargetSandbox + " is incompatible with the previous value of"
17169                                + oldTargetSandbox + ".");
17170                        return;
17171                    }
17172
17173                    // Prevent installing of child packages
17174                    if (oldPackage.parentPackage != null) {
17175                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17176                                "Package " + pkg.packageName + " is child of package "
17177                                        + oldPackage.parentPackage + ". Child packages "
17178                                        + "can be updated only through the parent package.");
17179                        return;
17180                    }
17181                }
17182            }
17183
17184            PackageSetting ps = mSettings.mPackages.get(pkgName);
17185            if (ps != null) {
17186                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17187
17188                // Static shared libs have same package with different versions where
17189                // we internally use a synthetic package name to allow multiple versions
17190                // of the same package, therefore we need to compare signatures against
17191                // the package setting for the latest library version.
17192                PackageSetting signatureCheckPs = ps;
17193                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17194                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17195                    if (libraryEntry != null) {
17196                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17197                    }
17198                }
17199
17200                // Quick sanity check that we're signed correctly if updating;
17201                // we'll check this again later when scanning, but we want to
17202                // bail early here before tripping over redefined permissions.
17203                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17204                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
17205                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
17206                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17207                                + pkg.packageName + " upgrade keys do not match the "
17208                                + "previously installed version");
17209                        return;
17210                    }
17211                } else {
17212                    try {
17213                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
17214                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
17215                        // We don't care about disabledPkgSetting on install for now.
17216                        final boolean compatMatch = verifySignatures(
17217                                signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
17218                                compareRecover);
17219                        // The new KeySets will be re-added later in the scanning process.
17220                        if (compatMatch) {
17221                            synchronized (mPackages) {
17222                                ksms.removeAppKeySetDataLPw(pkg.packageName);
17223                            }
17224                        }
17225                    } catch (PackageManagerException e) {
17226                        res.setError(e.error, e.getMessage());
17227                        return;
17228                    }
17229                }
17230
17231                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17232                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17233                    systemApp = (ps.pkg.applicationInfo.flags &
17234                            ApplicationInfo.FLAG_SYSTEM) != 0;
17235                }
17236                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17237            }
17238
17239            int N = pkg.permissions.size();
17240            for (int i = N-1; i >= 0; i--) {
17241                final PackageParser.Permission perm = pkg.permissions.get(i);
17242                final BasePermission bp =
17243                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
17244
17245                // Don't allow anyone but the system to define ephemeral permissions.
17246                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
17247                        && !systemApp) {
17248                    Slog.w(TAG, "Non-System package " + pkg.packageName
17249                            + " attempting to delcare ephemeral permission "
17250                            + perm.info.name + "; Removing ephemeral.");
17251                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
17252                }
17253
17254                // Check whether the newly-scanned package wants to define an already-defined perm
17255                if (bp != null) {
17256                    // If the defining package is signed with our cert, it's okay.  This
17257                    // also includes the "updating the same package" case, of course.
17258                    // "updating same package" could also involve key-rotation.
17259                    final boolean sigsOk;
17260                    final String sourcePackageName = bp.getSourcePackageName();
17261                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17262                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17263                    if (sourcePackageName.equals(pkg.packageName)
17264                            && (ksms.shouldCheckUpgradeKeySetLocked(
17265                                    sourcePackageSetting, scanFlags))) {
17266                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
17267                    } else {
17268
17269                        // in the event of signing certificate rotation, we need to see if the
17270                        // package's certificate has rotated from the current one, or if it is an
17271                        // older certificate with which the current is ok with sharing permissions
17272                        if (sourcePackageSetting.signatures.mSigningDetails.checkCapability(
17273                                        pkg.mSigningDetails,
17274                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17275                            sigsOk = true;
17276                        } else if (pkg.mSigningDetails.checkCapability(
17277                                        sourcePackageSetting.signatures.mSigningDetails,
17278                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17279
17280                            // the scanned package checks out, has signing certificate rotation
17281                            // history, and is newer; bring it over
17282                            sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails;
17283                            sigsOk = true;
17284                        } else {
17285                            sigsOk = false;
17286                        }
17287                    }
17288                    if (!sigsOk) {
17289                        // If the owning package is the system itself, we log but allow
17290                        // install to proceed; we fail the install on all other permission
17291                        // redefinitions.
17292                        if (!sourcePackageName.equals("android")) {
17293                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17294                                    + pkg.packageName + " attempting to redeclare permission "
17295                                    + perm.info.name + " already owned by " + sourcePackageName);
17296                            res.origPermission = perm.info.name;
17297                            res.origPackage = sourcePackageName;
17298                            return;
17299                        } else {
17300                            Slog.w(TAG, "Package " + pkg.packageName
17301                                    + " attempting to redeclare system permission "
17302                                    + perm.info.name + "; ignoring new declaration");
17303                            pkg.permissions.remove(i);
17304                        }
17305                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17306                        // Prevent apps to change protection level to dangerous from any other
17307                        // type as this would allow a privilege escalation where an app adds a
17308                        // normal/signature permission in other app's group and later redefines
17309                        // it as dangerous leading to the group auto-grant.
17310                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17311                                == PermissionInfo.PROTECTION_DANGEROUS) {
17312                            if (bp != null && !bp.isRuntime()) {
17313                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17314                                        + "non-runtime permission " + perm.info.name
17315                                        + " to runtime; keeping old protection level");
17316                                perm.info.protectionLevel = bp.getProtectionLevel();
17317                            }
17318                        }
17319                    }
17320                }
17321            }
17322        }
17323
17324        if (systemApp) {
17325            if (onExternal) {
17326                // Abort update; system app can't be replaced with app on sdcard
17327                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17328                        "Cannot install updates to system apps on sdcard");
17329                return;
17330            } else if (instantApp) {
17331                // Abort update; system app can't be replaced with an instant app
17332                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17333                        "Cannot update a system app with an instant app");
17334                return;
17335            }
17336        }
17337
17338        if (args.move != null) {
17339            // We did an in-place move, so dex is ready to roll
17340            scanFlags |= SCAN_NO_DEX;
17341            scanFlags |= SCAN_MOVE;
17342
17343            synchronized (mPackages) {
17344                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17345                if (ps == null) {
17346                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17347                            "Missing settings for moved package " + pkgName);
17348                }
17349
17350                // We moved the entire application as-is, so bring over the
17351                // previously derived ABI information.
17352                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17353                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17354            }
17355
17356        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17357            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17358            scanFlags |= SCAN_NO_DEX;
17359
17360            try {
17361                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17362                    args.abiOverride : pkg.cpuAbiOverride);
17363                final boolean extractNativeLibs = !pkg.isLibrary();
17364                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
17365            } catch (PackageManagerException pme) {
17366                Slog.e(TAG, "Error deriving application ABI", pme);
17367                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17368                return;
17369            }
17370
17371            // Shared libraries for the package need to be updated.
17372            synchronized (mPackages) {
17373                try {
17374                    updateSharedLibrariesLPr(pkg, null);
17375                } catch (PackageManagerException e) {
17376                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17377                }
17378            }
17379        }
17380
17381        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17382            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17383            return;
17384        }
17385
17386        if (PackageManagerServiceUtils.isApkVerityEnabled()) {
17387            String apkPath = null;
17388            synchronized (mPackages) {
17389                // Note that if the attacker managed to skip verify setup, for example by tampering
17390                // with the package settings, upon reboot we will do full apk verification when
17391                // verity is not detected.
17392                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17393                if (ps != null && ps.isPrivileged()) {
17394                    apkPath = pkg.baseCodePath;
17395                }
17396            }
17397
17398            if (apkPath != null) {
17399                final VerityUtils.SetupResult result =
17400                        VerityUtils.generateApkVeritySetupData(apkPath);
17401                if (result.isOk()) {
17402                    if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath);
17403                    FileDescriptor fd = result.getUnownedFileDescriptor();
17404                    try {
17405                        final byte[] signedRootHash = VerityUtils.generateFsverityRootHash(apkPath);
17406                        mInstaller.installApkVerity(apkPath, fd, result.getContentSize());
17407                        mInstaller.assertFsverityRootHashMatches(apkPath, signedRootHash);
17408                    } catch (InstallerException | IOException | DigestException |
17409                             NoSuchAlgorithmException e) {
17410                        res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17411                                "Failed to set up verity: " + e);
17412                        return;
17413                    } finally {
17414                        IoUtils.closeQuietly(fd);
17415                    }
17416                } else if (result.isFailed()) {
17417                    res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity");
17418                    return;
17419                } else {
17420                    // Do nothing if verity is skipped. Will fall back to full apk verification on
17421                    // reboot.
17422                }
17423            }
17424        }
17425
17426        if (!instantApp) {
17427            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17428        } else {
17429            if (DEBUG_DOMAIN_VERIFICATION) {
17430                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17431            }
17432        }
17433
17434        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17435                "installPackageLI")) {
17436            if (replace) {
17437                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17438                    // Static libs have a synthetic package name containing the version
17439                    // and cannot be updated as an update would get a new package name,
17440                    // unless this is the exact same version code which is useful for
17441                    // development.
17442                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17443                    if (existingPkg != null &&
17444                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
17445                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17446                                + "static-shared libs cannot be updated");
17447                        return;
17448                    }
17449                }
17450                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
17451                        installerPackageName, res, args.installReason);
17452            } else {
17453                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17454                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17455            }
17456        }
17457
17458        // Prepare the application profiles for the new code paths.
17459        // This needs to be done before invoking dexopt so that any install-time profile
17460        // can be used for optimizations.
17461        mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier()));
17462
17463        // Check whether we need to dexopt the app.
17464        //
17465        // NOTE: it is IMPORTANT to call dexopt:
17466        //   - after doRename which will sync the package data from PackageParser.Package and its
17467        //     corresponding ApplicationInfo.
17468        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
17469        //     uid of the application (pkg.applicationInfo.uid).
17470        //     This update happens in place!
17471        //
17472        // We only need to dexopt if the package meets ALL of the following conditions:
17473        //   1) it is not forward locked.
17474        //   2) it is not on on an external ASEC container.
17475        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17476        //   4) it is not debuggable.
17477        //
17478        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17479        // complete, so we skip this step during installation. Instead, we'll take extra time
17480        // the first time the instant app starts. It's preferred to do it this way to provide
17481        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17482        // middle of running an instant app. The default behaviour can be overridden
17483        // via gservices.
17484        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
17485                && !forwardLocked
17486                && !pkg.applicationInfo.isExternalAsec()
17487                && (!instantApp || Global.getInt(mContext.getContentResolver(),
17488                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0)
17489                && ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0);
17490
17491        if (performDexopt) {
17492            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17493            // Do not run PackageDexOptimizer through the local performDexOpt
17494            // method because `pkg` may not be in `mPackages` yet.
17495            //
17496            // Also, don't fail application installs if the dexopt step fails.
17497            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17498                    REASON_INSTALL,
17499                    DexoptOptions.DEXOPT_BOOT_COMPLETE |
17500                    DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE);
17501            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17502                    null /* instructionSets */,
17503                    getOrCreateCompilerPackageStats(pkg),
17504                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17505                    dexoptOptions);
17506            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17507        }
17508
17509        // Notify BackgroundDexOptService that the package has been changed.
17510        // If this is an update of a package which used to fail to compile,
17511        // BackgroundDexOptService will remove it from its blacklist.
17512        // TODO: Layering violation
17513        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17514
17515        synchronized (mPackages) {
17516            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17517            if (ps != null) {
17518                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17519                ps.setUpdateAvailable(false /*updateAvailable*/);
17520            }
17521
17522            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17523            for (int i = 0; i < childCount; i++) {
17524                PackageParser.Package childPkg = pkg.childPackages.get(i);
17525                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17526                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17527                if (childPs != null) {
17528                    childRes.newUsers = childPs.queryInstalledUsers(
17529                            sUserManager.getUserIds(), true);
17530                }
17531            }
17532
17533            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17534                updateSequenceNumberLP(ps, res.newUsers);
17535                updateInstantAppInstallerLocked(pkgName);
17536            }
17537        }
17538    }
17539
17540    private void startIntentFilterVerifications(int userId, boolean replacing,
17541            PackageParser.Package pkg) {
17542        if (mIntentFilterVerifierComponent == null) {
17543            Slog.w(TAG, "No IntentFilter verification will not be done as "
17544                    + "there is no IntentFilterVerifier available!");
17545            return;
17546        }
17547
17548        final int verifierUid = getPackageUid(
17549                mIntentFilterVerifierComponent.getPackageName(),
17550                MATCH_DEBUG_TRIAGED_MISSING,
17551                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17552
17553        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17554        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17555        mHandler.sendMessage(msg);
17556
17557        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17558        for (int i = 0; i < childCount; i++) {
17559            PackageParser.Package childPkg = pkg.childPackages.get(i);
17560            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17561            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17562            mHandler.sendMessage(msg);
17563        }
17564    }
17565
17566    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17567            PackageParser.Package pkg) {
17568        int size = pkg.activities.size();
17569        if (size == 0) {
17570            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17571                    "No activity, so no need to verify any IntentFilter!");
17572            return;
17573        }
17574
17575        final boolean hasDomainURLs = hasDomainURLs(pkg);
17576        if (!hasDomainURLs) {
17577            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17578                    "No domain URLs, so no need to verify any IntentFilter!");
17579            return;
17580        }
17581
17582        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17583                + " if any IntentFilter from the " + size
17584                + " Activities needs verification ...");
17585
17586        int count = 0;
17587        final String packageName = pkg.packageName;
17588
17589        synchronized (mPackages) {
17590            // If this is a new install and we see that we've already run verification for this
17591            // package, we have nothing to do: it means the state was restored from backup.
17592            if (!replacing) {
17593                IntentFilterVerificationInfo ivi =
17594                        mSettings.getIntentFilterVerificationLPr(packageName);
17595                if (ivi != null) {
17596                    if (DEBUG_DOMAIN_VERIFICATION) {
17597                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17598                                + ivi.getStatusString());
17599                    }
17600                    return;
17601                }
17602            }
17603
17604            // If any filters need to be verified, then all need to be.
17605            boolean needToVerify = false;
17606            for (PackageParser.Activity a : pkg.activities) {
17607                for (ActivityIntentInfo filter : a.intents) {
17608                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17609                        if (DEBUG_DOMAIN_VERIFICATION) {
17610                            Slog.d(TAG,
17611                                    "Intent filter needs verification, so processing all filters");
17612                        }
17613                        needToVerify = true;
17614                        break;
17615                    }
17616                }
17617            }
17618
17619            if (needToVerify) {
17620                final int verificationId = mIntentFilterVerificationToken++;
17621                for (PackageParser.Activity a : pkg.activities) {
17622                    for (ActivityIntentInfo filter : a.intents) {
17623                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17624                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17625                                    "Verification needed for IntentFilter:" + filter.toString());
17626                            mIntentFilterVerifier.addOneIntentFilterVerification(
17627                                    verifierUid, userId, verificationId, filter, packageName);
17628                            count++;
17629                        }
17630                    }
17631                }
17632            }
17633        }
17634
17635        if (count > 0) {
17636            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17637                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17638                    +  " for userId:" + userId);
17639            mIntentFilterVerifier.startVerifications(userId);
17640        } else {
17641            if (DEBUG_DOMAIN_VERIFICATION) {
17642                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17643            }
17644        }
17645    }
17646
17647    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17648        final ComponentName cn  = filter.activity.getComponentName();
17649        final String packageName = cn.getPackageName();
17650
17651        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17652                packageName);
17653        if (ivi == null) {
17654            return true;
17655        }
17656        int status = ivi.getStatus();
17657        switch (status) {
17658            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17659            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17660                return true;
17661
17662            default:
17663                // Nothing to do
17664                return false;
17665        }
17666    }
17667
17668    private static boolean isMultiArch(ApplicationInfo info) {
17669        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17670    }
17671
17672    private static boolean isExternal(PackageParser.Package pkg) {
17673        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17674    }
17675
17676    private static boolean isExternal(PackageSetting ps) {
17677        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17678    }
17679
17680    private static boolean isSystemApp(PackageParser.Package pkg) {
17681        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17682    }
17683
17684    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17685        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17686    }
17687
17688    private static boolean isOemApp(PackageParser.Package pkg) {
17689        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17690    }
17691
17692    private static boolean isVendorApp(PackageParser.Package pkg) {
17693        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17694    }
17695
17696    private static boolean isProductApp(PackageParser.Package pkg) {
17697        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
17698    }
17699
17700    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17701        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17702    }
17703
17704    private static boolean isSystemApp(PackageSetting ps) {
17705        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17706    }
17707
17708    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17709        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17710    }
17711
17712    private int packageFlagsToInstallFlags(PackageSetting ps) {
17713        int installFlags = 0;
17714        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17715            // This existing package was an external ASEC install when we have
17716            // the external flag without a UUID
17717            installFlags |= PackageManager.INSTALL_EXTERNAL;
17718        }
17719        if (ps.isForwardLocked()) {
17720            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17721        }
17722        return installFlags;
17723    }
17724
17725    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17726        if (isExternal(pkg)) {
17727            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17728                return mSettings.getExternalVersion();
17729            } else {
17730                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17731            }
17732        } else {
17733            return mSettings.getInternalVersion();
17734        }
17735    }
17736
17737    private void deleteTempPackageFiles() {
17738        final FilenameFilter filter = new FilenameFilter() {
17739            public boolean accept(File dir, String name) {
17740                return name.startsWith("vmdl") && name.endsWith(".tmp");
17741            }
17742        };
17743        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17744            file.delete();
17745        }
17746    }
17747
17748    @Override
17749    public void deletePackageAsUser(String packageName, int versionCode,
17750            IPackageDeleteObserver observer, int userId, int flags) {
17751        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17752                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17753    }
17754
17755    @Override
17756    public void deletePackageVersioned(VersionedPackage versionedPackage,
17757            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17758        final int callingUid = Binder.getCallingUid();
17759        mContext.enforceCallingOrSelfPermission(
17760                android.Manifest.permission.DELETE_PACKAGES, null);
17761        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17762        Preconditions.checkNotNull(versionedPackage);
17763        Preconditions.checkNotNull(observer);
17764        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17765                PackageManager.VERSION_CODE_HIGHEST,
17766                Long.MAX_VALUE, "versionCode must be >= -1");
17767
17768        final String packageName = versionedPackage.getPackageName();
17769        final long versionCode = versionedPackage.getLongVersionCode();
17770        final String internalPackageName;
17771        synchronized (mPackages) {
17772            // Normalize package name to handle renamed packages and static libs
17773            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17774        }
17775
17776        final int uid = Binder.getCallingUid();
17777        if (!isOrphaned(internalPackageName)
17778                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17779            try {
17780                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17781                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17782                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17783                observer.onUserActionRequired(intent);
17784            } catch (RemoteException re) {
17785            }
17786            return;
17787        }
17788        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17789        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17790        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17791            mContext.enforceCallingOrSelfPermission(
17792                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17793                    "deletePackage for user " + userId);
17794        }
17795
17796        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17797            try {
17798                observer.onPackageDeleted(packageName,
17799                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17800            } catch (RemoteException re) {
17801            }
17802            return;
17803        }
17804
17805        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17806            try {
17807                observer.onPackageDeleted(packageName,
17808                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17809            } catch (RemoteException re) {
17810            }
17811            return;
17812        }
17813
17814        if (DEBUG_REMOVE) {
17815            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17816                    + " deleteAllUsers: " + deleteAllUsers + " version="
17817                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17818                    ? "VERSION_CODE_HIGHEST" : versionCode));
17819        }
17820        // Queue up an async operation since the package deletion may take a little while.
17821        mHandler.post(new Runnable() {
17822            public void run() {
17823                mHandler.removeCallbacks(this);
17824                int returnCode;
17825                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17826                boolean doDeletePackage = true;
17827                if (ps != null) {
17828                    final boolean targetIsInstantApp =
17829                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17830                    doDeletePackage = !targetIsInstantApp
17831                            || canViewInstantApps;
17832                }
17833                if (doDeletePackage) {
17834                    if (!deleteAllUsers) {
17835                        returnCode = deletePackageX(internalPackageName, versionCode,
17836                                userId, deleteFlags);
17837                    } else {
17838                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17839                                internalPackageName, users);
17840                        // If nobody is blocking uninstall, proceed with delete for all users
17841                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17842                            returnCode = deletePackageX(internalPackageName, versionCode,
17843                                    userId, deleteFlags);
17844                        } else {
17845                            // Otherwise uninstall individually for users with blockUninstalls=false
17846                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17847                            for (int userId : users) {
17848                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17849                                    returnCode = deletePackageX(internalPackageName, versionCode,
17850                                            userId, userFlags);
17851                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17852                                        Slog.w(TAG, "Package delete failed for user " + userId
17853                                                + ", returnCode " + returnCode);
17854                                    }
17855                                }
17856                            }
17857                            // The app has only been marked uninstalled for certain users.
17858                            // We still need to report that delete was blocked
17859                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17860                        }
17861                    }
17862                } else {
17863                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17864                }
17865                try {
17866                    observer.onPackageDeleted(packageName, returnCode, null);
17867                } catch (RemoteException e) {
17868                    Log.i(TAG, "Observer no longer exists.");
17869                } //end catch
17870            } //end run
17871        });
17872    }
17873
17874    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17875        if (pkg.staticSharedLibName != null) {
17876            return pkg.manifestPackageName;
17877        }
17878        return pkg.packageName;
17879    }
17880
17881    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17882        // Handle renamed packages
17883        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17884        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17885
17886        // Is this a static library?
17887        LongSparseArray<SharedLibraryEntry> versionedLib =
17888                mStaticLibsByDeclaringPackage.get(packageName);
17889        if (versionedLib == null || versionedLib.size() <= 0) {
17890            return packageName;
17891        }
17892
17893        // Figure out which lib versions the caller can see
17894        LongSparseLongArray versionsCallerCanSee = null;
17895        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17896        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17897                && callingAppId != Process.ROOT_UID) {
17898            versionsCallerCanSee = new LongSparseLongArray();
17899            String libName = versionedLib.valueAt(0).info.getName();
17900            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17901            if (uidPackages != null) {
17902                for (String uidPackage : uidPackages) {
17903                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17904                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17905                    if (libIdx >= 0) {
17906                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17907                        versionsCallerCanSee.append(libVersion, libVersion);
17908                    }
17909                }
17910            }
17911        }
17912
17913        // Caller can see nothing - done
17914        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17915            return packageName;
17916        }
17917
17918        // Find the version the caller can see and the app version code
17919        SharedLibraryEntry highestVersion = null;
17920        final int versionCount = versionedLib.size();
17921        for (int i = 0; i < versionCount; i++) {
17922            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17923            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17924                    libEntry.info.getLongVersion()) < 0) {
17925                continue;
17926            }
17927            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17928            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17929                if (libVersionCode == versionCode) {
17930                    return libEntry.apk;
17931                }
17932            } else if (highestVersion == null) {
17933                highestVersion = libEntry;
17934            } else if (libVersionCode  > highestVersion.info
17935                    .getDeclaringPackage().getLongVersionCode()) {
17936                highestVersion = libEntry;
17937            }
17938        }
17939
17940        if (highestVersion != null) {
17941            return highestVersion.apk;
17942        }
17943
17944        return packageName;
17945    }
17946
17947    boolean isCallerVerifier(int callingUid) {
17948        final int callingUserId = UserHandle.getUserId(callingUid);
17949        return mRequiredVerifierPackage != null &&
17950                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17951    }
17952
17953    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17954        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17955              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17956            return true;
17957        }
17958        final int callingUserId = UserHandle.getUserId(callingUid);
17959        // If the caller installed the pkgName, then allow it to silently uninstall.
17960        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17961            return true;
17962        }
17963
17964        // Allow package verifier to silently uninstall.
17965        if (mRequiredVerifierPackage != null &&
17966                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17967            return true;
17968        }
17969
17970        // Allow package uninstaller to silently uninstall.
17971        if (mRequiredUninstallerPackage != null &&
17972                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17973            return true;
17974        }
17975
17976        // Allow storage manager to silently uninstall.
17977        if (mStorageManagerPackage != null &&
17978                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17979            return true;
17980        }
17981
17982        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17983        // uninstall for device owner provisioning.
17984        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17985                == PERMISSION_GRANTED) {
17986            return true;
17987        }
17988
17989        return false;
17990    }
17991
17992    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17993        int[] result = EMPTY_INT_ARRAY;
17994        for (int userId : userIds) {
17995            if (getBlockUninstallForUser(packageName, userId)) {
17996                result = ArrayUtils.appendInt(result, userId);
17997            }
17998        }
17999        return result;
18000    }
18001
18002    @Override
18003    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18004        final int callingUid = Binder.getCallingUid();
18005        if (getInstantAppPackageName(callingUid) != null
18006                && !isCallerSameApp(packageName, callingUid)) {
18007            return false;
18008        }
18009        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18010    }
18011
18012    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18013        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18014                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18015        try {
18016            if (dpm != null) {
18017                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18018                        /* callingUserOnly =*/ false);
18019                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18020                        : deviceOwnerComponentName.getPackageName();
18021                // Does the package contains the device owner?
18022                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18023                // this check is probably not needed, since DO should be registered as a device
18024                // admin on some user too. (Original bug for this: b/17657954)
18025                if (packageName.equals(deviceOwnerPackageName)) {
18026                    return true;
18027                }
18028                // Does it contain a device admin for any user?
18029                int[] users;
18030                if (userId == UserHandle.USER_ALL) {
18031                    users = sUserManager.getUserIds();
18032                } else {
18033                    users = new int[]{userId};
18034                }
18035                for (int i = 0; i < users.length; ++i) {
18036                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18037                        return true;
18038                    }
18039                }
18040            }
18041        } catch (RemoteException e) {
18042        }
18043        return false;
18044    }
18045
18046    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18047        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18048    }
18049
18050    /**
18051     *  This method is an internal method that could be get invoked either
18052     *  to delete an installed package or to clean up a failed installation.
18053     *  After deleting an installed package, a broadcast is sent to notify any
18054     *  listeners that the package has been removed. For cleaning up a failed
18055     *  installation, the broadcast is not necessary since the package's
18056     *  installation wouldn't have sent the initial broadcast either
18057     *  The key steps in deleting a package are
18058     *  deleting the package information in internal structures like mPackages,
18059     *  deleting the packages base directories through installd
18060     *  updating mSettings to reflect current status
18061     *  persisting settings for later use
18062     *  sending a broadcast if necessary
18063     */
18064    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
18065        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18066        final boolean res;
18067
18068        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18069                ? UserHandle.USER_ALL : userId;
18070
18071        if (isPackageDeviceAdmin(packageName, removeUser)) {
18072            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18073            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18074        }
18075
18076        PackageSetting uninstalledPs = null;
18077        PackageParser.Package pkg = null;
18078
18079        // for the uninstall-updates case and restricted profiles, remember the per-
18080        // user handle installed state
18081        int[] allUsers;
18082        synchronized (mPackages) {
18083            uninstalledPs = mSettings.mPackages.get(packageName);
18084            if (uninstalledPs == null) {
18085                Slog.w(TAG, "Not removing non-existent package " + packageName);
18086                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18087            }
18088
18089            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18090                    && uninstalledPs.versionCode != versionCode) {
18091                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18092                        + uninstalledPs.versionCode + " != " + versionCode);
18093                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18094            }
18095
18096            // Static shared libs can be declared by any package, so let us not
18097            // allow removing a package if it provides a lib others depend on.
18098            pkg = mPackages.get(packageName);
18099
18100            allUsers = sUserManager.getUserIds();
18101
18102            if (pkg != null && pkg.staticSharedLibName != null) {
18103                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18104                        pkg.staticSharedLibVersion);
18105                if (libEntry != null) {
18106                    for (int currUserId : allUsers) {
18107                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18108                            continue;
18109                        }
18110                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18111                                libEntry.info, 0, currUserId);
18112                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18113                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18114                                    + " hosting lib " + libEntry.info.getName() + " version "
18115                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
18116                                    + " for user " + currUserId);
18117                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18118                        }
18119                    }
18120                }
18121            }
18122
18123            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18124        }
18125
18126        final int freezeUser;
18127        if (isUpdatedSystemApp(uninstalledPs)
18128                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18129            // We're downgrading a system app, which will apply to all users, so
18130            // freeze them all during the downgrade
18131            freezeUser = UserHandle.USER_ALL;
18132        } else {
18133            freezeUser = removeUser;
18134        }
18135
18136        synchronized (mInstallLock) {
18137            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18138            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18139                    deleteFlags, "deletePackageX")) {
18140                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18141                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
18142            }
18143            synchronized (mPackages) {
18144                if (res) {
18145                    if (pkg != null) {
18146                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18147                    }
18148                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18149                    updateInstantAppInstallerLocked(packageName);
18150                }
18151            }
18152        }
18153
18154        if (res) {
18155            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18156            info.sendPackageRemovedBroadcasts(killApp);
18157            info.sendSystemPackageUpdatedBroadcasts();
18158            info.sendSystemPackageAppearedBroadcasts();
18159        }
18160        // Force a gc here.
18161        Runtime.getRuntime().gc();
18162        // Delete the resources here after sending the broadcast to let
18163        // other processes clean up before deleting resources.
18164        if (info.args != null) {
18165            synchronized (mInstallLock) {
18166                info.args.doPostDeleteLI(true);
18167            }
18168        }
18169
18170        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18171    }
18172
18173    static class PackageRemovedInfo {
18174        final PackageSender packageSender;
18175        String removedPackage;
18176        String installerPackageName;
18177        int uid = -1;
18178        int removedAppId = -1;
18179        int[] origUsers;
18180        int[] removedUsers = null;
18181        int[] broadcastUsers = null;
18182        int[] instantUserIds = null;
18183        SparseArray<Integer> installReasons;
18184        boolean isRemovedPackageSystemUpdate = false;
18185        boolean isUpdate;
18186        boolean dataRemoved;
18187        boolean removedForAllUsers;
18188        boolean isStaticSharedLib;
18189        // Clean up resources deleted packages.
18190        InstallArgs args = null;
18191        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18192        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18193
18194        PackageRemovedInfo(PackageSender packageSender) {
18195            this.packageSender = packageSender;
18196        }
18197
18198        void sendPackageRemovedBroadcasts(boolean killApp) {
18199            sendPackageRemovedBroadcastInternal(killApp);
18200            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18201            for (int i = 0; i < childCount; i++) {
18202                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18203                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18204            }
18205        }
18206
18207        void sendSystemPackageUpdatedBroadcasts() {
18208            if (isRemovedPackageSystemUpdate) {
18209                sendSystemPackageUpdatedBroadcastsInternal();
18210                final int childCount = (removedChildPackages != null)
18211                        ? removedChildPackages.size() : 0;
18212                for (int i = 0; i < childCount; i++) {
18213                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18214                    if (childInfo.isRemovedPackageSystemUpdate) {
18215                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18216                    }
18217                }
18218            }
18219        }
18220
18221        void sendSystemPackageAppearedBroadcasts() {
18222            final int packageCount = (appearedChildPackages != null)
18223                    ? appearedChildPackages.size() : 0;
18224            for (int i = 0; i < packageCount; i++) {
18225                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18226                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18227                    true /*sendBootCompleted*/, false /*startReceiver*/,
18228                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
18229            }
18230        }
18231
18232        private void sendSystemPackageUpdatedBroadcastsInternal() {
18233            Bundle extras = new Bundle(2);
18234            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18235            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18236            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18237                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18238            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18239                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18240            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18241                null, null, 0, removedPackage, null, null, null);
18242            if (installerPackageName != null) {
18243                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18244                        removedPackage, extras, 0 /*flags*/,
18245                        installerPackageName, null, null, null);
18246                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18247                        removedPackage, extras, 0 /*flags*/,
18248                        installerPackageName, null, null, null);
18249            }
18250        }
18251
18252        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18253            // Don't send static shared library removal broadcasts as these
18254            // libs are visible only the the apps that depend on them an one
18255            // cannot remove the library if it has a dependency.
18256            if (isStaticSharedLib) {
18257                return;
18258            }
18259            Bundle extras = new Bundle(2);
18260            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18261            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18262            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18263            if (isUpdate || isRemovedPackageSystemUpdate) {
18264                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18265            }
18266            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18267            if (removedPackage != null) {
18268                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18269                    removedPackage, extras, 0, null /*targetPackage*/, null,
18270                    broadcastUsers, instantUserIds);
18271                if (installerPackageName != null) {
18272                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18273                            removedPackage, extras, 0 /*flags*/,
18274                            installerPackageName, null, broadcastUsers, instantUserIds);
18275                }
18276                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18277                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18278                        removedPackage, extras,
18279                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18280                        null, null, broadcastUsers, instantUserIds);
18281                    packageSender.notifyPackageRemoved(removedPackage);
18282                }
18283            }
18284            if (removedAppId >= 0) {
18285                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18286                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18287                    null, null, broadcastUsers, instantUserIds);
18288            }
18289        }
18290
18291        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18292            removedUsers = userIds;
18293            if (removedUsers == null) {
18294                broadcastUsers = null;
18295                return;
18296            }
18297
18298            broadcastUsers = EMPTY_INT_ARRAY;
18299            instantUserIds = EMPTY_INT_ARRAY;
18300            for (int i = userIds.length - 1; i >= 0; --i) {
18301                final int userId = userIds[i];
18302                if (deletedPackageSetting.getInstantApp(userId)) {
18303                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
18304                } else {
18305                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18306                }
18307            }
18308        }
18309    }
18310
18311    /*
18312     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18313     * flag is not set, the data directory is removed as well.
18314     * make sure this flag is set for partially installed apps. If not its meaningless to
18315     * delete a partially installed application.
18316     */
18317    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18318            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18319        String packageName = ps.name;
18320        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18321        // Retrieve object to delete permissions for shared user later on
18322        final PackageParser.Package deletedPkg;
18323        final PackageSetting deletedPs;
18324        // reader
18325        synchronized (mPackages) {
18326            deletedPkg = mPackages.get(packageName);
18327            deletedPs = mSettings.mPackages.get(packageName);
18328            if (outInfo != null) {
18329                outInfo.removedPackage = packageName;
18330                outInfo.installerPackageName = ps.installerPackageName;
18331                outInfo.isStaticSharedLib = deletedPkg != null
18332                        && deletedPkg.staticSharedLibName != null;
18333                outInfo.populateUsers(deletedPs == null ? null
18334                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18335            }
18336        }
18337
18338        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
18339
18340        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18341            final PackageParser.Package resolvedPkg;
18342            if (deletedPkg != null) {
18343                resolvedPkg = deletedPkg;
18344            } else {
18345                // We don't have a parsed package when it lives on an ejected
18346                // adopted storage device, so fake something together
18347                resolvedPkg = new PackageParser.Package(ps.name);
18348                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18349            }
18350            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18351                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18352            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18353            if (outInfo != null) {
18354                outInfo.dataRemoved = true;
18355            }
18356            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18357        }
18358
18359        int removedAppId = -1;
18360
18361        // writer
18362        synchronized (mPackages) {
18363            boolean installedStateChanged = false;
18364            if (deletedPs != null) {
18365                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18366                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18367                    clearDefaultBrowserIfNeeded(packageName);
18368                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18369                    removedAppId = mSettings.removePackageLPw(packageName);
18370                    if (outInfo != null) {
18371                        outInfo.removedAppId = removedAppId;
18372                    }
18373                    mPermissionManager.updatePermissions(
18374                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
18375                    if (deletedPs.sharedUser != null) {
18376                        // Remove permissions associated with package. Since runtime
18377                        // permissions are per user we have to kill the removed package
18378                        // or packages running under the shared user of the removed
18379                        // package if revoking the permissions requested only by the removed
18380                        // package is successful and this causes a change in gids.
18381                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18382                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18383                                    userId);
18384                            if (userIdToKill == UserHandle.USER_ALL
18385                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18386                                // If gids changed for this user, kill all affected packages.
18387                                mHandler.post(new Runnable() {
18388                                    @Override
18389                                    public void run() {
18390                                        // This has to happen with no lock held.
18391                                        killApplication(deletedPs.name, deletedPs.appId,
18392                                                KILL_APP_REASON_GIDS_CHANGED);
18393                                    }
18394                                });
18395                                break;
18396                            }
18397                        }
18398                    }
18399                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18400                }
18401                // make sure to preserve per-user disabled state if this removal was just
18402                // a downgrade of a system app to the factory package
18403                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18404                    if (DEBUG_REMOVE) {
18405                        Slog.d(TAG, "Propagating install state across downgrade");
18406                    }
18407                    for (int userId : allUserHandles) {
18408                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18409                        if (DEBUG_REMOVE) {
18410                            Slog.d(TAG, "    user " + userId + " => " + installed);
18411                        }
18412                        if (installed != ps.getInstalled(userId)) {
18413                            installedStateChanged = true;
18414                        }
18415                        ps.setInstalled(installed, userId);
18416                    }
18417                }
18418            }
18419            // can downgrade to reader
18420            if (writeSettings) {
18421                // Save settings now
18422                mSettings.writeLPr();
18423            }
18424            if (installedStateChanged) {
18425                mSettings.writeKernelMappingLPr(ps);
18426            }
18427        }
18428        if (removedAppId != -1) {
18429            // A user ID was deleted here. Go through all users and remove it
18430            // from KeyStore.
18431            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18432        }
18433    }
18434
18435    static boolean locationIsPrivileged(String path) {
18436        try {
18437            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
18438            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
18439            final File privilegedOdmAppDir = new File(Environment.getOdmDirectory(), "priv-app");
18440            final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
18441            return path.startsWith(privilegedAppDir.getCanonicalPath())
18442                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath())
18443                    || path.startsWith(privilegedOdmAppDir.getCanonicalPath())
18444                    || path.startsWith(privilegedProductAppDir.getCanonicalPath());
18445        } catch (IOException e) {
18446            Slog.e(TAG, "Unable to access code path " + path);
18447        }
18448        return false;
18449    }
18450
18451    static boolean locationIsOem(String path) {
18452        try {
18453            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
18454        } catch (IOException e) {
18455            Slog.e(TAG, "Unable to access code path " + path);
18456        }
18457        return false;
18458    }
18459
18460    static boolean locationIsVendor(String path) {
18461        try {
18462            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath())
18463                    || path.startsWith(Environment.getOdmDirectory().getCanonicalPath());
18464        } catch (IOException e) {
18465            Slog.e(TAG, "Unable to access code path " + path);
18466        }
18467        return false;
18468    }
18469
18470    static boolean locationIsProduct(String path) {
18471        try {
18472            return path.startsWith(Environment.getProductDirectory().getCanonicalPath());
18473        } catch (IOException e) {
18474            Slog.e(TAG, "Unable to access code path " + path);
18475        }
18476        return false;
18477    }
18478
18479    /*
18480     * Tries to delete system package.
18481     */
18482    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18483            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18484            boolean writeSettings) {
18485        if (deletedPs.parentPackageName != null) {
18486            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18487            return false;
18488        }
18489
18490        final boolean applyUserRestrictions
18491                = (allUserHandles != null) && (outInfo.origUsers != null);
18492        final PackageSetting disabledPs;
18493        // Confirm if the system package has been updated
18494        // An updated system app can be deleted. This will also have to restore
18495        // the system pkg from system partition
18496        // reader
18497        synchronized (mPackages) {
18498            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18499        }
18500
18501        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18502                + " disabledPs=" + disabledPs);
18503
18504        if (disabledPs == null) {
18505            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18506            return false;
18507        } else if (DEBUG_REMOVE) {
18508            Slog.d(TAG, "Deleting system pkg from data partition");
18509        }
18510
18511        if (DEBUG_REMOVE) {
18512            if (applyUserRestrictions) {
18513                Slog.d(TAG, "Remembering install states:");
18514                for (int userId : allUserHandles) {
18515                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18516                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18517                }
18518            }
18519        }
18520
18521        // Delete the updated package
18522        outInfo.isRemovedPackageSystemUpdate = true;
18523        if (outInfo.removedChildPackages != null) {
18524            final int childCount = (deletedPs.childPackageNames != null)
18525                    ? deletedPs.childPackageNames.size() : 0;
18526            for (int i = 0; i < childCount; i++) {
18527                String childPackageName = deletedPs.childPackageNames.get(i);
18528                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18529                        .contains(childPackageName)) {
18530                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18531                            childPackageName);
18532                    if (childInfo != null) {
18533                        childInfo.isRemovedPackageSystemUpdate = true;
18534                    }
18535                }
18536            }
18537        }
18538
18539        if (disabledPs.versionCode < deletedPs.versionCode) {
18540            // Delete data for downgrades
18541            flags &= ~PackageManager.DELETE_KEEP_DATA;
18542        } else {
18543            // Preserve data by setting flag
18544            flags |= PackageManager.DELETE_KEEP_DATA;
18545        }
18546
18547        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18548                outInfo, writeSettings, disabledPs.pkg);
18549        if (!ret) {
18550            return false;
18551        }
18552
18553        // writer
18554        synchronized (mPackages) {
18555            // NOTE: The system package always needs to be enabled; even if it's for
18556            // a compressed stub. If we don't, installing the system package fails
18557            // during scan [scanning checks the disabled packages]. We will reverse
18558            // this later, after we've "installed" the stub.
18559            // Reinstate the old system package
18560            enableSystemPackageLPw(disabledPs.pkg);
18561            // Remove any native libraries from the upgraded package.
18562            removeNativeBinariesLI(deletedPs);
18563        }
18564
18565        // Install the system package
18566        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18567        try {
18568            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
18569                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18570        } catch (PackageManagerException e) {
18571            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18572                    + e.getMessage());
18573            return false;
18574        } finally {
18575            if (disabledPs.pkg.isStub) {
18576                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18577            }
18578        }
18579        return true;
18580    }
18581
18582    /**
18583     * Installs a package that's already on the system partition.
18584     */
18585    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
18586            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18587            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18588                    throws PackageManagerException {
18589        @ParseFlags int parseFlags =
18590                mDefParseFlags
18591                | PackageParser.PARSE_MUST_BE_APK
18592                | PackageParser.PARSE_IS_SYSTEM_DIR;
18593        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
18594        if (isPrivileged || locationIsPrivileged(codePathString)) {
18595            scanFlags |= SCAN_AS_PRIVILEGED;
18596        }
18597        if (locationIsOem(codePathString)) {
18598            scanFlags |= SCAN_AS_OEM;
18599        }
18600        if (locationIsVendor(codePathString)) {
18601            scanFlags |= SCAN_AS_VENDOR;
18602        }
18603        if (locationIsProduct(codePathString)) {
18604            scanFlags |= SCAN_AS_PRODUCT;
18605        }
18606
18607        final File codePath = new File(codePathString);
18608        final PackageParser.Package pkg =
18609                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
18610
18611        try {
18612            // update shared libraries for the newly re-installed system package
18613            updateSharedLibrariesLPr(pkg, null);
18614        } catch (PackageManagerException e) {
18615            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18616        }
18617
18618        prepareAppDataAfterInstallLIF(pkg);
18619
18620        // writer
18621        synchronized (mPackages) {
18622            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18623
18624            // Propagate the permissions state as we do not want to drop on the floor
18625            // runtime permissions. The update permissions method below will take
18626            // care of removing obsolete permissions and grant install permissions.
18627            if (origPermissionState != null) {
18628                ps.getPermissionsState().copyFrom(origPermissionState);
18629            }
18630            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18631                    mPermissionCallback);
18632
18633            final boolean applyUserRestrictions
18634                    = (allUserHandles != null) && (origUserHandles != null);
18635            if (applyUserRestrictions) {
18636                boolean installedStateChanged = false;
18637                if (DEBUG_REMOVE) {
18638                    Slog.d(TAG, "Propagating install state across reinstall");
18639                }
18640                for (int userId : allUserHandles) {
18641                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18642                    if (DEBUG_REMOVE) {
18643                        Slog.d(TAG, "    user " + userId + " => " + installed);
18644                    }
18645                    if (installed != ps.getInstalled(userId)) {
18646                        installedStateChanged = true;
18647                    }
18648                    ps.setInstalled(installed, userId);
18649
18650                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18651                }
18652                // Regardless of writeSettings we need to ensure that this restriction
18653                // state propagation is persisted
18654                mSettings.writeAllUsersPackageRestrictionsLPr();
18655                if (installedStateChanged) {
18656                    mSettings.writeKernelMappingLPr(ps);
18657                }
18658            }
18659            // can downgrade to reader here
18660            if (writeSettings) {
18661                mSettings.writeLPr();
18662            }
18663        }
18664        return pkg;
18665    }
18666
18667    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18668            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18669            PackageRemovedInfo outInfo, boolean writeSettings,
18670            PackageParser.Package replacingPackage) {
18671        synchronized (mPackages) {
18672            if (outInfo != null) {
18673                outInfo.uid = ps.appId;
18674            }
18675
18676            if (outInfo != null && outInfo.removedChildPackages != null) {
18677                final int childCount = (ps.childPackageNames != null)
18678                        ? ps.childPackageNames.size() : 0;
18679                for (int i = 0; i < childCount; i++) {
18680                    String childPackageName = ps.childPackageNames.get(i);
18681                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18682                    if (childPs == null) {
18683                        return false;
18684                    }
18685                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18686                            childPackageName);
18687                    if (childInfo != null) {
18688                        childInfo.uid = childPs.appId;
18689                    }
18690                }
18691            }
18692        }
18693
18694        // Delete package data from internal structures and also remove data if flag is set
18695        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18696
18697        // Delete the child packages data
18698        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18699        for (int i = 0; i < childCount; i++) {
18700            PackageSetting childPs;
18701            synchronized (mPackages) {
18702                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18703            }
18704            if (childPs != null) {
18705                PackageRemovedInfo childOutInfo = (outInfo != null
18706                        && outInfo.removedChildPackages != null)
18707                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18708                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18709                        && (replacingPackage != null
18710                        && !replacingPackage.hasChildPackage(childPs.name))
18711                        ? flags & ~DELETE_KEEP_DATA : flags;
18712                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18713                        deleteFlags, writeSettings);
18714            }
18715        }
18716
18717        // Delete application code and resources only for parent packages
18718        if (ps.parentPackageName == null) {
18719            if (deleteCodeAndResources && (outInfo != null)) {
18720                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18721                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18722                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18723            }
18724        }
18725
18726        return true;
18727    }
18728
18729    @Override
18730    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18731            int userId) {
18732        mContext.enforceCallingOrSelfPermission(
18733                android.Manifest.permission.DELETE_PACKAGES, null);
18734        synchronized (mPackages) {
18735            // Cannot block uninstall of static shared libs as they are
18736            // considered a part of the using app (emulating static linking).
18737            // Also static libs are installed always on internal storage.
18738            PackageParser.Package pkg = mPackages.get(packageName);
18739            if (pkg != null && pkg.staticSharedLibName != null) {
18740                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18741                        + " providing static shared library: " + pkg.staticSharedLibName);
18742                return false;
18743            }
18744            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18745            mSettings.writePackageRestrictionsLPr(userId);
18746        }
18747        return true;
18748    }
18749
18750    @Override
18751    public boolean getBlockUninstallForUser(String packageName, int userId) {
18752        synchronized (mPackages) {
18753            final PackageSetting ps = mSettings.mPackages.get(packageName);
18754            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18755                return false;
18756            }
18757            return mSettings.getBlockUninstallLPr(userId, packageName);
18758        }
18759    }
18760
18761    @Override
18762    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18763        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18764        synchronized (mPackages) {
18765            PackageSetting ps = mSettings.mPackages.get(packageName);
18766            if (ps == null) {
18767                Log.w(TAG, "Package doesn't exist: " + packageName);
18768                return false;
18769            }
18770            if (systemUserApp) {
18771                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18772            } else {
18773                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18774            }
18775            mSettings.writeLPr();
18776        }
18777        return true;
18778    }
18779
18780    /*
18781     * This method handles package deletion in general
18782     */
18783    private boolean deletePackageLIF(String packageName, UserHandle user,
18784            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18785            PackageRemovedInfo outInfo, boolean writeSettings,
18786            PackageParser.Package replacingPackage) {
18787        if (packageName == null) {
18788            Slog.w(TAG, "Attempt to delete null packageName.");
18789            return false;
18790        }
18791
18792        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18793
18794        PackageSetting ps;
18795        synchronized (mPackages) {
18796            ps = mSettings.mPackages.get(packageName);
18797            if (ps == null) {
18798                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18799                return false;
18800            }
18801
18802            if (ps.parentPackageName != null && (!isSystemApp(ps)
18803                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18804                if (DEBUG_REMOVE) {
18805                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18806                            + ((user == null) ? UserHandle.USER_ALL : user));
18807                }
18808                final int removedUserId = (user != null) ? user.getIdentifier()
18809                        : UserHandle.USER_ALL;
18810
18811                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18812                    return false;
18813                }
18814                markPackageUninstalledForUserLPw(ps, user);
18815                scheduleWritePackageRestrictionsLocked(user);
18816                return true;
18817            }
18818        }
18819
18820        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
18821        if (ps.getPermissionsState().hasPermission(Manifest.permission.SUSPEND_APPS, userId)) {
18822            unsuspendForSuspendingPackage(packageName, userId);
18823        }
18824
18825
18826        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18827                && user.getIdentifier() != UserHandle.USER_ALL)) {
18828            // The caller is asking that the package only be deleted for a single
18829            // user.  To do this, we just mark its uninstalled state and delete
18830            // its data. If this is a system app, we only allow this to happen if
18831            // they have set the special DELETE_SYSTEM_APP which requests different
18832            // semantics than normal for uninstalling system apps.
18833            markPackageUninstalledForUserLPw(ps, user);
18834
18835            if (!isSystemApp(ps)) {
18836                // Do not uninstall the APK if an app should be cached
18837                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18838                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18839                    // Other user still have this package installed, so all
18840                    // we need to do is clear this user's data and save that
18841                    // it is uninstalled.
18842                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18843                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18844                        return false;
18845                    }
18846                    scheduleWritePackageRestrictionsLocked(user);
18847                    return true;
18848                } else {
18849                    // We need to set it back to 'installed' so the uninstall
18850                    // broadcasts will be sent correctly.
18851                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18852                    ps.setInstalled(true, user.getIdentifier());
18853                    mSettings.writeKernelMappingLPr(ps);
18854                }
18855            } else {
18856                // This is a system app, so we assume that the
18857                // other users still have this package installed, so all
18858                // we need to do is clear this user's data and save that
18859                // it is uninstalled.
18860                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18861                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18862                    return false;
18863                }
18864                scheduleWritePackageRestrictionsLocked(user);
18865                return true;
18866            }
18867        }
18868
18869        // If we are deleting a composite package for all users, keep track
18870        // of result for each child.
18871        if (ps.childPackageNames != null && outInfo != null) {
18872            synchronized (mPackages) {
18873                final int childCount = ps.childPackageNames.size();
18874                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18875                for (int i = 0; i < childCount; i++) {
18876                    String childPackageName = ps.childPackageNames.get(i);
18877                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18878                    childInfo.removedPackage = childPackageName;
18879                    childInfo.installerPackageName = ps.installerPackageName;
18880                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18881                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18882                    if (childPs != null) {
18883                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18884                    }
18885                }
18886            }
18887        }
18888
18889        boolean ret = false;
18890        if (isSystemApp(ps)) {
18891            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18892            // When an updated system application is deleted we delete the existing resources
18893            // as well and fall back to existing code in system partition
18894            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18895        } else {
18896            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18897            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18898                    outInfo, writeSettings, replacingPackage);
18899        }
18900
18901        // Take a note whether we deleted the package for all users
18902        if (outInfo != null) {
18903            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18904            if (outInfo.removedChildPackages != null) {
18905                synchronized (mPackages) {
18906                    final int childCount = outInfo.removedChildPackages.size();
18907                    for (int i = 0; i < childCount; i++) {
18908                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18909                        if (childInfo != null) {
18910                            childInfo.removedForAllUsers = mPackages.get(
18911                                    childInfo.removedPackage) == null;
18912                        }
18913                    }
18914                }
18915            }
18916            // If we uninstalled an update to a system app there may be some
18917            // child packages that appeared as they are declared in the system
18918            // app but were not declared in the update.
18919            if (isSystemApp(ps)) {
18920                synchronized (mPackages) {
18921                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18922                    final int childCount = (updatedPs.childPackageNames != null)
18923                            ? updatedPs.childPackageNames.size() : 0;
18924                    for (int i = 0; i < childCount; i++) {
18925                        String childPackageName = updatedPs.childPackageNames.get(i);
18926                        if (outInfo.removedChildPackages == null
18927                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18928                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18929                            if (childPs == null) {
18930                                continue;
18931                            }
18932                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18933                            installRes.name = childPackageName;
18934                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18935                            installRes.pkg = mPackages.get(childPackageName);
18936                            installRes.uid = childPs.pkg.applicationInfo.uid;
18937                            if (outInfo.appearedChildPackages == null) {
18938                                outInfo.appearedChildPackages = new ArrayMap<>();
18939                            }
18940                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18941                        }
18942                    }
18943                }
18944            }
18945        }
18946
18947        return ret;
18948    }
18949
18950    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18951        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18952                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18953        for (int nextUserId : userIds) {
18954            if (DEBUG_REMOVE) {
18955                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18956            }
18957            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18958                    false /*installed*/,
18959                    true /*stopped*/,
18960                    true /*notLaunched*/,
18961                    false /*hidden*/,
18962                    false /*suspended*/,
18963                    null /*suspendingPackage*/,
18964                    null /*dialogMessage*/,
18965                    null /*suspendedAppExtras*/,
18966                    null /*suspendedLauncherExtras*/,
18967                    false /*instantApp*/,
18968                    false /*virtualPreload*/,
18969                    null /*lastDisableAppCaller*/,
18970                    null /*enabledComponents*/,
18971                    null /*disabledComponents*/,
18972                    ps.readUserState(nextUserId).domainVerificationStatus,
18973                    0, PackageManager.INSTALL_REASON_UNKNOWN,
18974                    null /*harmfulAppWarning*/);
18975        }
18976        mSettings.writeKernelMappingLPr(ps);
18977    }
18978
18979    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18980            PackageRemovedInfo outInfo) {
18981        final PackageParser.Package pkg;
18982        synchronized (mPackages) {
18983            pkg = mPackages.get(ps.name);
18984        }
18985
18986        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18987                : new int[] {userId};
18988        for (int nextUserId : userIds) {
18989            if (DEBUG_REMOVE) {
18990                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18991                        + nextUserId);
18992            }
18993
18994            destroyAppDataLIF(pkg, userId,
18995                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18996            destroyAppProfilesLIF(pkg, userId);
18997            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18998            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18999            schedulePackageCleaning(ps.name, nextUserId, false);
19000            synchronized (mPackages) {
19001                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19002                    scheduleWritePackageRestrictionsLocked(nextUserId);
19003                }
19004                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19005            }
19006        }
19007
19008        if (outInfo != null) {
19009            outInfo.removedPackage = ps.name;
19010            outInfo.installerPackageName = ps.installerPackageName;
19011            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19012            outInfo.removedAppId = ps.appId;
19013            outInfo.removedUsers = userIds;
19014            outInfo.broadcastUsers = userIds;
19015        }
19016
19017        return true;
19018    }
19019
19020    private final class ClearStorageConnection implements ServiceConnection {
19021        IMediaContainerService mContainerService;
19022
19023        @Override
19024        public void onServiceConnected(ComponentName name, IBinder service) {
19025            synchronized (this) {
19026                mContainerService = IMediaContainerService.Stub
19027                        .asInterface(Binder.allowBlocking(service));
19028                notifyAll();
19029            }
19030        }
19031
19032        @Override
19033        public void onServiceDisconnected(ComponentName name) {
19034        }
19035    }
19036
19037    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19038        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19039
19040        final boolean mounted;
19041        if (Environment.isExternalStorageEmulated()) {
19042            mounted = true;
19043        } else {
19044            final String status = Environment.getExternalStorageState();
19045
19046            mounted = status.equals(Environment.MEDIA_MOUNTED)
19047                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19048        }
19049
19050        if (!mounted) {
19051            return;
19052        }
19053
19054        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19055        int[] users;
19056        if (userId == UserHandle.USER_ALL) {
19057            users = sUserManager.getUserIds();
19058        } else {
19059            users = new int[] { userId };
19060        }
19061        final ClearStorageConnection conn = new ClearStorageConnection();
19062        if (mContext.bindServiceAsUser(
19063                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19064            try {
19065                for (int curUser : users) {
19066                    long timeout = SystemClock.uptimeMillis() + 5000;
19067                    synchronized (conn) {
19068                        long now;
19069                        while (conn.mContainerService == null &&
19070                                (now = SystemClock.uptimeMillis()) < timeout) {
19071                            try {
19072                                conn.wait(timeout - now);
19073                            } catch (InterruptedException e) {
19074                            }
19075                        }
19076                    }
19077                    if (conn.mContainerService == null) {
19078                        return;
19079                    }
19080
19081                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19082                    clearDirectory(conn.mContainerService,
19083                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19084                    if (allData) {
19085                        clearDirectory(conn.mContainerService,
19086                                userEnv.buildExternalStorageAppDataDirs(packageName));
19087                        clearDirectory(conn.mContainerService,
19088                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19089                    }
19090                }
19091            } finally {
19092                mContext.unbindService(conn);
19093            }
19094        }
19095    }
19096
19097    @Override
19098    public void clearApplicationProfileData(String packageName) {
19099        enforceSystemOrRoot("Only the system can clear all profile data");
19100
19101        final PackageParser.Package pkg;
19102        synchronized (mPackages) {
19103            pkg = mPackages.get(packageName);
19104        }
19105
19106        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19107            synchronized (mInstallLock) {
19108                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19109            }
19110        }
19111    }
19112
19113    @Override
19114    public void clearApplicationUserData(final String packageName,
19115            final IPackageDataObserver observer, final int userId) {
19116        mContext.enforceCallingOrSelfPermission(
19117                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19118
19119        final int callingUid = Binder.getCallingUid();
19120        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19121                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19122
19123        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19124        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
19125        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19126            throw new SecurityException("Cannot clear data for a protected package: "
19127                    + packageName);
19128        }
19129        // Queue up an async operation since the package deletion may take a little while.
19130        mHandler.post(new Runnable() {
19131            public void run() {
19132                mHandler.removeCallbacks(this);
19133                final boolean succeeded;
19134                if (!filterApp) {
19135                    try (PackageFreezer freezer = freezePackage(packageName,
19136                            "clearApplicationUserData")) {
19137                        synchronized (mInstallLock) {
19138                            succeeded = clearApplicationUserDataLIF(packageName, userId);
19139                        }
19140                        clearExternalStorageDataSync(packageName, userId, true);
19141                        synchronized (mPackages) {
19142                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19143                                    packageName, userId);
19144                        }
19145                    }
19146                    if (succeeded) {
19147                        // invoke DeviceStorageMonitor's update method to clear any notifications
19148                        DeviceStorageMonitorInternal dsm = LocalServices
19149                                .getService(DeviceStorageMonitorInternal.class);
19150                        if (dsm != null) {
19151                            dsm.checkMemory();
19152                        }
19153                        if (checkPermission(Manifest.permission.SUSPEND_APPS, packageName, userId)
19154                                == PERMISSION_GRANTED) {
19155                            unsuspendForSuspendingPackage(packageName, userId);
19156                        }
19157                    }
19158                } else {
19159                    succeeded = false;
19160                }
19161                if (observer != null) {
19162                    try {
19163                        observer.onRemoveCompleted(packageName, succeeded);
19164                    } catch (RemoteException e) {
19165                        Log.i(TAG, "Observer no longer exists.");
19166                    }
19167                } //end if observer
19168            } //end run
19169        });
19170    }
19171
19172    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19173        if (packageName == null) {
19174            Slog.w(TAG, "Attempt to delete null packageName.");
19175            return false;
19176        }
19177
19178        // Try finding details about the requested package
19179        PackageParser.Package pkg;
19180        synchronized (mPackages) {
19181            pkg = mPackages.get(packageName);
19182            if (pkg == null) {
19183                final PackageSetting ps = mSettings.mPackages.get(packageName);
19184                if (ps != null) {
19185                    pkg = ps.pkg;
19186                }
19187            }
19188
19189            if (pkg == null) {
19190                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19191                return false;
19192            }
19193
19194            PackageSetting ps = (PackageSetting) pkg.mExtras;
19195            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19196        }
19197
19198        clearAppDataLIF(pkg, userId,
19199                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19200
19201        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19202        removeKeystoreDataIfNeeded(userId, appId);
19203
19204        UserManagerInternal umInternal = getUserManagerInternal();
19205        final int flags;
19206        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19207            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19208        } else if (umInternal.isUserRunning(userId)) {
19209            flags = StorageManager.FLAG_STORAGE_DE;
19210        } else {
19211            flags = 0;
19212        }
19213        prepareAppDataContentsLIF(pkg, userId, flags);
19214
19215        return true;
19216    }
19217
19218    /**
19219     * Reverts user permission state changes (permissions and flags) in
19220     * all packages for a given user.
19221     *
19222     * @param userId The device user for which to do a reset.
19223     */
19224    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19225        final int packageCount = mPackages.size();
19226        for (int i = 0; i < packageCount; i++) {
19227            PackageParser.Package pkg = mPackages.valueAt(i);
19228            PackageSetting ps = (PackageSetting) pkg.mExtras;
19229            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19230        }
19231    }
19232
19233    private void resetNetworkPolicies(int userId) {
19234        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19235    }
19236
19237    /**
19238     * Reverts user permission state changes (permissions and flags).
19239     *
19240     * @param ps The package for which to reset.
19241     * @param userId The device user for which to do a reset.
19242     */
19243    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19244            final PackageSetting ps, final int userId) {
19245        if (ps.pkg == null) {
19246            return;
19247        }
19248
19249        // These are flags that can change base on user actions.
19250        final int userSettableMask = FLAG_PERMISSION_USER_SET
19251                | FLAG_PERMISSION_USER_FIXED
19252                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19253                | FLAG_PERMISSION_REVIEW_REQUIRED;
19254
19255        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19256                | FLAG_PERMISSION_POLICY_FIXED;
19257
19258        boolean writeInstallPermissions = false;
19259        boolean writeRuntimePermissions = false;
19260
19261        final int permissionCount = ps.pkg.requestedPermissions.size();
19262        for (int i = 0; i < permissionCount; i++) {
19263            final String permName = ps.pkg.requestedPermissions.get(i);
19264            final BasePermission bp =
19265                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19266            if (bp == null) {
19267                continue;
19268            }
19269
19270            // If shared user we just reset the state to which only this app contributed.
19271            if (ps.sharedUser != null) {
19272                boolean used = false;
19273                final int packageCount = ps.sharedUser.packages.size();
19274                for (int j = 0; j < packageCount; j++) {
19275                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19276                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19277                            && pkg.pkg.requestedPermissions.contains(permName)) {
19278                        used = true;
19279                        break;
19280                    }
19281                }
19282                if (used) {
19283                    continue;
19284                }
19285            }
19286
19287            final PermissionsState permissionsState = ps.getPermissionsState();
19288
19289            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19290
19291            // Always clear the user settable flags.
19292            final boolean hasInstallState =
19293                    permissionsState.getInstallPermissionState(permName) != null;
19294            // If permission review is enabled and this is a legacy app, mark the
19295            // permission as requiring a review as this is the initial state.
19296            int flags = 0;
19297            if (mSettings.mPermissions.mPermissionReviewRequired
19298                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19299                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19300            }
19301            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19302                if (hasInstallState) {
19303                    writeInstallPermissions = true;
19304                } else {
19305                    writeRuntimePermissions = true;
19306                }
19307            }
19308
19309            // Below is only runtime permission handling.
19310            if (!bp.isRuntime()) {
19311                continue;
19312            }
19313
19314            // Never clobber system or policy.
19315            if ((oldFlags & policyOrSystemFlags) != 0) {
19316                continue;
19317            }
19318
19319            // If this permission was granted by default, make sure it is.
19320            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19321                if (permissionsState.grantRuntimePermission(bp, userId)
19322                        != PERMISSION_OPERATION_FAILURE) {
19323                    writeRuntimePermissions = true;
19324                }
19325            // If permission review is enabled the permissions for a legacy apps
19326            // are represented as constantly granted runtime ones, so don't revoke.
19327            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19328                // Otherwise, reset the permission.
19329                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19330                switch (revokeResult) {
19331                    case PERMISSION_OPERATION_SUCCESS:
19332                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19333                        writeRuntimePermissions = true;
19334                        final int appId = ps.appId;
19335                        mHandler.post(new Runnable() {
19336                            @Override
19337                            public void run() {
19338                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19339                            }
19340                        });
19341                    } break;
19342                }
19343            }
19344        }
19345
19346        // Synchronously write as we are taking permissions away.
19347        if (writeRuntimePermissions) {
19348            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19349        }
19350
19351        // Synchronously write as we are taking permissions away.
19352        if (writeInstallPermissions) {
19353            mSettings.writeLPr();
19354        }
19355    }
19356
19357    /**
19358     * Remove entries from the keystore daemon. Will only remove it if the
19359     * {@code appId} is valid.
19360     */
19361    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19362        if (appId < 0) {
19363            return;
19364        }
19365
19366        final KeyStore keyStore = KeyStore.getInstance();
19367        if (keyStore != null) {
19368            if (userId == UserHandle.USER_ALL) {
19369                for (final int individual : sUserManager.getUserIds()) {
19370                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19371                }
19372            } else {
19373                keyStore.clearUid(UserHandle.getUid(userId, appId));
19374            }
19375        } else {
19376            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19377        }
19378    }
19379
19380    @Override
19381    public void deleteApplicationCacheFiles(final String packageName,
19382            final IPackageDataObserver observer) {
19383        final int userId = UserHandle.getCallingUserId();
19384        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19385    }
19386
19387    @Override
19388    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19389            final IPackageDataObserver observer) {
19390        final int callingUid = Binder.getCallingUid();
19391        if (mContext.checkCallingOrSelfPermission(
19392                android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES)
19393                != PackageManager.PERMISSION_GRANTED) {
19394            // If the caller has the old delete cache permission, silently ignore.  Else throw.
19395            if (mContext.checkCallingOrSelfPermission(
19396                    android.Manifest.permission.DELETE_CACHE_FILES)
19397                    == PackageManager.PERMISSION_GRANTED) {
19398                Slog.w(TAG, "Calling uid " + callingUid + " does not have " +
19399                        android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES +
19400                        ", silently ignoring");
19401                return;
19402            }
19403            mContext.enforceCallingOrSelfPermission(
19404                    android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES, null);
19405        }
19406        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19407                /* requireFullPermission= */ true, /* checkShell= */ false,
19408                "delete application cache files");
19409        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19410                android.Manifest.permission.ACCESS_INSTANT_APPS);
19411
19412        final PackageParser.Package pkg;
19413        synchronized (mPackages) {
19414            pkg = mPackages.get(packageName);
19415        }
19416
19417        // Queue up an async operation since the package deletion may take a little while.
19418        mHandler.post(new Runnable() {
19419            public void run() {
19420                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19421                boolean doClearData = true;
19422                if (ps != null) {
19423                    final boolean targetIsInstantApp =
19424                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19425                    doClearData = !targetIsInstantApp
19426                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19427                }
19428                if (doClearData) {
19429                    synchronized (mInstallLock) {
19430                        final int flags = StorageManager.FLAG_STORAGE_DE
19431                                | StorageManager.FLAG_STORAGE_CE;
19432                        // We're only clearing cache files, so we don't care if the
19433                        // app is unfrozen and still able to run
19434                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19435                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19436                    }
19437                    clearExternalStorageDataSync(packageName, userId, false);
19438                }
19439                if (observer != null) {
19440                    try {
19441                        observer.onRemoveCompleted(packageName, true);
19442                    } catch (RemoteException e) {
19443                        Log.i(TAG, "Observer no longer exists.");
19444                    }
19445                }
19446            }
19447        });
19448    }
19449
19450    @Override
19451    public void getPackageSizeInfo(final String packageName, int userHandle,
19452            final IPackageStatsObserver observer) {
19453        throw new UnsupportedOperationException(
19454                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19455    }
19456
19457    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19458        final PackageSetting ps;
19459        synchronized (mPackages) {
19460            ps = mSettings.mPackages.get(packageName);
19461            if (ps == null) {
19462                Slog.w(TAG, "Failed to find settings for " + packageName);
19463                return false;
19464            }
19465        }
19466
19467        final String[] packageNames = { packageName };
19468        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19469        final String[] codePaths = { ps.codePathString };
19470
19471        try {
19472            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19473                    ps.appId, ceDataInodes, codePaths, stats);
19474
19475            // For now, ignore code size of packages on system partition
19476            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19477                stats.codeSize = 0;
19478            }
19479
19480            // External clients expect these to be tracked separately
19481            stats.dataSize -= stats.cacheSize;
19482
19483        } catch (InstallerException e) {
19484            Slog.w(TAG, String.valueOf(e));
19485            return false;
19486        }
19487
19488        return true;
19489    }
19490
19491    private int getUidTargetSdkVersionLockedLPr(int uid) {
19492        Object obj = mSettings.getUserIdLPr(uid);
19493        if (obj instanceof SharedUserSetting) {
19494            final SharedUserSetting sus = (SharedUserSetting) obj;
19495            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19496            final Iterator<PackageSetting> it = sus.packages.iterator();
19497            while (it.hasNext()) {
19498                final PackageSetting ps = it.next();
19499                if (ps.pkg != null) {
19500                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19501                    if (v < vers) vers = v;
19502                }
19503            }
19504            return vers;
19505        } else if (obj instanceof PackageSetting) {
19506            final PackageSetting ps = (PackageSetting) obj;
19507            if (ps.pkg != null) {
19508                return ps.pkg.applicationInfo.targetSdkVersion;
19509            }
19510        }
19511        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19512    }
19513
19514    private int getPackageTargetSdkVersionLockedLPr(String packageName) {
19515        final PackageParser.Package p = mPackages.get(packageName);
19516        if (p != null) {
19517            return p.applicationInfo.targetSdkVersion;
19518        }
19519        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19520    }
19521
19522    @Override
19523    public void addPreferredActivity(IntentFilter filter, int match,
19524            ComponentName[] set, ComponentName activity, int userId) {
19525        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19526                "Adding preferred");
19527    }
19528
19529    private void addPreferredActivityInternal(IntentFilter filter, int match,
19530            ComponentName[] set, ComponentName activity, boolean always, int userId,
19531            String opname) {
19532        // writer
19533        int callingUid = Binder.getCallingUid();
19534        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19535                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19536        if (filter.countActions() == 0) {
19537            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19538            return;
19539        }
19540        synchronized (mPackages) {
19541            if (mContext.checkCallingOrSelfPermission(
19542                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19543                    != PackageManager.PERMISSION_GRANTED) {
19544                if (getUidTargetSdkVersionLockedLPr(callingUid)
19545                        < Build.VERSION_CODES.FROYO) {
19546                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19547                            + callingUid);
19548                    return;
19549                }
19550                mContext.enforceCallingOrSelfPermission(
19551                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19552            }
19553
19554            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19555            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19556                    + userId + ":");
19557            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19558            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19559            scheduleWritePackageRestrictionsLocked(userId);
19560            postPreferredActivityChangedBroadcast(userId);
19561        }
19562    }
19563
19564    private void postPreferredActivityChangedBroadcast(int userId) {
19565        mHandler.post(() -> {
19566            final IActivityManager am = ActivityManager.getService();
19567            if (am == null) {
19568                return;
19569            }
19570
19571            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19572            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19573            try {
19574                am.broadcastIntent(null, intent, null, null,
19575                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19576                        null, false, false, userId);
19577            } catch (RemoteException e) {
19578            }
19579        });
19580    }
19581
19582    @Override
19583    public void replacePreferredActivity(IntentFilter filter, int match,
19584            ComponentName[] set, ComponentName activity, int userId) {
19585        if (filter.countActions() != 1) {
19586            throw new IllegalArgumentException(
19587                    "replacePreferredActivity expects filter to have only 1 action.");
19588        }
19589        if (filter.countDataAuthorities() != 0
19590                || filter.countDataPaths() != 0
19591                || filter.countDataSchemes() > 1
19592                || filter.countDataTypes() != 0) {
19593            throw new IllegalArgumentException(
19594                    "replacePreferredActivity expects filter to have no data authorities, " +
19595                    "paths, or types; and at most one scheme.");
19596        }
19597
19598        final int callingUid = Binder.getCallingUid();
19599        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19600                true /* requireFullPermission */, false /* checkShell */,
19601                "replace preferred activity");
19602        synchronized (mPackages) {
19603            if (mContext.checkCallingOrSelfPermission(
19604                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19605                    != PackageManager.PERMISSION_GRANTED) {
19606                if (getUidTargetSdkVersionLockedLPr(callingUid)
19607                        < Build.VERSION_CODES.FROYO) {
19608                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19609                            + Binder.getCallingUid());
19610                    return;
19611                }
19612                mContext.enforceCallingOrSelfPermission(
19613                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19614            }
19615
19616            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19617            if (pir != null) {
19618                // Get all of the existing entries that exactly match this filter.
19619                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19620                if (existing != null && existing.size() == 1) {
19621                    PreferredActivity cur = existing.get(0);
19622                    if (DEBUG_PREFERRED) {
19623                        Slog.i(TAG, "Checking replace of preferred:");
19624                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19625                        if (!cur.mPref.mAlways) {
19626                            Slog.i(TAG, "  -- CUR; not mAlways!");
19627                        } else {
19628                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19629                            Slog.i(TAG, "  -- CUR: mSet="
19630                                    + Arrays.toString(cur.mPref.mSetComponents));
19631                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19632                            Slog.i(TAG, "  -- NEW: mMatch="
19633                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19634                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19635                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19636                        }
19637                    }
19638                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19639                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19640                            && cur.mPref.sameSet(set)) {
19641                        // Setting the preferred activity to what it happens to be already
19642                        if (DEBUG_PREFERRED) {
19643                            Slog.i(TAG, "Replacing with same preferred activity "
19644                                    + cur.mPref.mShortComponent + " for user "
19645                                    + userId + ":");
19646                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19647                        }
19648                        return;
19649                    }
19650                }
19651
19652                if (existing != null) {
19653                    if (DEBUG_PREFERRED) {
19654                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19655                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19656                    }
19657                    for (int i = 0; i < existing.size(); i++) {
19658                        PreferredActivity pa = existing.get(i);
19659                        if (DEBUG_PREFERRED) {
19660                            Slog.i(TAG, "Removing existing preferred activity "
19661                                    + pa.mPref.mComponent + ":");
19662                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19663                        }
19664                        pir.removeFilter(pa);
19665                    }
19666                }
19667            }
19668            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19669                    "Replacing preferred");
19670        }
19671    }
19672
19673    @Override
19674    public void clearPackagePreferredActivities(String packageName) {
19675        final int callingUid = Binder.getCallingUid();
19676        if (getInstantAppPackageName(callingUid) != null) {
19677            return;
19678        }
19679        // writer
19680        synchronized (mPackages) {
19681            PackageParser.Package pkg = mPackages.get(packageName);
19682            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19683                if (mContext.checkCallingOrSelfPermission(
19684                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19685                        != PackageManager.PERMISSION_GRANTED) {
19686                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19687                            < Build.VERSION_CODES.FROYO) {
19688                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19689                                + callingUid);
19690                        return;
19691                    }
19692                    mContext.enforceCallingOrSelfPermission(
19693                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19694                }
19695            }
19696            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19697            if (ps != null
19698                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19699                return;
19700            }
19701            int user = UserHandle.getCallingUserId();
19702            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19703                scheduleWritePackageRestrictionsLocked(user);
19704            }
19705        }
19706    }
19707
19708    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19709    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19710        ArrayList<PreferredActivity> removed = null;
19711        boolean changed = false;
19712        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19713            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19714            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19715            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19716                continue;
19717            }
19718            Iterator<PreferredActivity> it = pir.filterIterator();
19719            while (it.hasNext()) {
19720                PreferredActivity pa = it.next();
19721                // Mark entry for removal only if it matches the package name
19722                // and the entry is of type "always".
19723                if (packageName == null ||
19724                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19725                                && pa.mPref.mAlways)) {
19726                    if (removed == null) {
19727                        removed = new ArrayList<PreferredActivity>();
19728                    }
19729                    removed.add(pa);
19730                }
19731            }
19732            if (removed != null) {
19733                for (int j=0; j<removed.size(); j++) {
19734                    PreferredActivity pa = removed.get(j);
19735                    pir.removeFilter(pa);
19736                }
19737                changed = true;
19738            }
19739        }
19740        if (changed) {
19741            postPreferredActivityChangedBroadcast(userId);
19742        }
19743        return changed;
19744    }
19745
19746    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19747    private void clearIntentFilterVerificationsLPw(int userId) {
19748        final int packageCount = mPackages.size();
19749        for (int i = 0; i < packageCount; i++) {
19750            PackageParser.Package pkg = mPackages.valueAt(i);
19751            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19752        }
19753    }
19754
19755    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19756    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19757        if (userId == UserHandle.USER_ALL) {
19758            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19759                    sUserManager.getUserIds())) {
19760                for (int oneUserId : sUserManager.getUserIds()) {
19761                    scheduleWritePackageRestrictionsLocked(oneUserId);
19762                }
19763            }
19764        } else {
19765            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19766                scheduleWritePackageRestrictionsLocked(userId);
19767            }
19768        }
19769    }
19770
19771    /** Clears state for all users, and touches intent filter verification policy */
19772    void clearDefaultBrowserIfNeeded(String packageName) {
19773        for (int oneUserId : sUserManager.getUserIds()) {
19774            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19775        }
19776    }
19777
19778    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19779        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19780        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19781            if (packageName.equals(defaultBrowserPackageName)) {
19782                setDefaultBrowserPackageName(null, userId);
19783            }
19784        }
19785    }
19786
19787    @Override
19788    public void resetApplicationPreferences(int userId) {
19789        mContext.enforceCallingOrSelfPermission(
19790                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19791        final long identity = Binder.clearCallingIdentity();
19792        // writer
19793        try {
19794            synchronized (mPackages) {
19795                clearPackagePreferredActivitiesLPw(null, userId);
19796                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19797                // TODO: We have to reset the default SMS and Phone. This requires
19798                // significant refactoring to keep all default apps in the package
19799                // manager (cleaner but more work) or have the services provide
19800                // callbacks to the package manager to request a default app reset.
19801                applyFactoryDefaultBrowserLPw(userId);
19802                clearIntentFilterVerificationsLPw(userId);
19803                primeDomainVerificationsLPw(userId);
19804                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19805                scheduleWritePackageRestrictionsLocked(userId);
19806            }
19807            resetNetworkPolicies(userId);
19808        } finally {
19809            Binder.restoreCallingIdentity(identity);
19810        }
19811    }
19812
19813    @Override
19814    public int getPreferredActivities(List<IntentFilter> outFilters,
19815            List<ComponentName> outActivities, String packageName) {
19816        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19817            return 0;
19818        }
19819        int num = 0;
19820        final int userId = UserHandle.getCallingUserId();
19821        // reader
19822        synchronized (mPackages) {
19823            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19824            if (pir != null) {
19825                final Iterator<PreferredActivity> it = pir.filterIterator();
19826                while (it.hasNext()) {
19827                    final PreferredActivity pa = it.next();
19828                    if (packageName == null
19829                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19830                                    && pa.mPref.mAlways)) {
19831                        if (outFilters != null) {
19832                            outFilters.add(new IntentFilter(pa));
19833                        }
19834                        if (outActivities != null) {
19835                            outActivities.add(pa.mPref.mComponent);
19836                        }
19837                    }
19838                }
19839            }
19840        }
19841
19842        return num;
19843    }
19844
19845    @Override
19846    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19847            int userId) {
19848        int callingUid = Binder.getCallingUid();
19849        if (callingUid != Process.SYSTEM_UID) {
19850            throw new SecurityException(
19851                    "addPersistentPreferredActivity can only be run by the system");
19852        }
19853        if (filter.countActions() == 0) {
19854            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19855            return;
19856        }
19857        synchronized (mPackages) {
19858            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19859                    ":");
19860            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19861            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19862                    new PersistentPreferredActivity(filter, activity));
19863            scheduleWritePackageRestrictionsLocked(userId);
19864            postPreferredActivityChangedBroadcast(userId);
19865        }
19866    }
19867
19868    @Override
19869    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19870        int callingUid = Binder.getCallingUid();
19871        if (callingUid != Process.SYSTEM_UID) {
19872            throw new SecurityException(
19873                    "clearPackagePersistentPreferredActivities can only be run by the system");
19874        }
19875        ArrayList<PersistentPreferredActivity> removed = null;
19876        boolean changed = false;
19877        synchronized (mPackages) {
19878            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19879                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19880                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19881                        .valueAt(i);
19882                if (userId != thisUserId) {
19883                    continue;
19884                }
19885                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19886                while (it.hasNext()) {
19887                    PersistentPreferredActivity ppa = it.next();
19888                    // Mark entry for removal only if it matches the package name.
19889                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19890                        if (removed == null) {
19891                            removed = new ArrayList<PersistentPreferredActivity>();
19892                        }
19893                        removed.add(ppa);
19894                    }
19895                }
19896                if (removed != null) {
19897                    for (int j=0; j<removed.size(); j++) {
19898                        PersistentPreferredActivity ppa = removed.get(j);
19899                        ppir.removeFilter(ppa);
19900                    }
19901                    changed = true;
19902                }
19903            }
19904
19905            if (changed) {
19906                scheduleWritePackageRestrictionsLocked(userId);
19907                postPreferredActivityChangedBroadcast(userId);
19908            }
19909        }
19910    }
19911
19912    /**
19913     * Common machinery for picking apart a restored XML blob and passing
19914     * it to a caller-supplied functor to be applied to the running system.
19915     */
19916    private void restoreFromXml(XmlPullParser parser, int userId,
19917            String expectedStartTag, BlobXmlRestorer functor)
19918            throws IOException, XmlPullParserException {
19919        int type;
19920        while ((type = parser.next()) != XmlPullParser.START_TAG
19921                && type != XmlPullParser.END_DOCUMENT) {
19922        }
19923        if (type != XmlPullParser.START_TAG) {
19924            // oops didn't find a start tag?!
19925            if (DEBUG_BACKUP) {
19926                Slog.e(TAG, "Didn't find start tag during restore");
19927            }
19928            return;
19929        }
19930Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19931        // this is supposed to be TAG_PREFERRED_BACKUP
19932        if (!expectedStartTag.equals(parser.getName())) {
19933            if (DEBUG_BACKUP) {
19934                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19935            }
19936            return;
19937        }
19938
19939        // skip interfering stuff, then we're aligned with the backing implementation
19940        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19941Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19942        functor.apply(parser, userId);
19943    }
19944
19945    private interface BlobXmlRestorer {
19946        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19947    }
19948
19949    /**
19950     * Non-Binder method, support for the backup/restore mechanism: write the
19951     * full set of preferred activities in its canonical XML format.  Returns the
19952     * XML output as a byte array, or null if there is none.
19953     */
19954    @Override
19955    public byte[] getPreferredActivityBackup(int userId) {
19956        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19957            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19958        }
19959
19960        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19961        try {
19962            final XmlSerializer serializer = new FastXmlSerializer();
19963            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19964            serializer.startDocument(null, true);
19965            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19966
19967            synchronized (mPackages) {
19968                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19969            }
19970
19971            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19972            serializer.endDocument();
19973            serializer.flush();
19974        } catch (Exception e) {
19975            if (DEBUG_BACKUP) {
19976                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19977            }
19978            return null;
19979        }
19980
19981        return dataStream.toByteArray();
19982    }
19983
19984    @Override
19985    public void restorePreferredActivities(byte[] backup, int userId) {
19986        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19987            throw new SecurityException("Only the system may call restorePreferredActivities()");
19988        }
19989
19990        try {
19991            final XmlPullParser parser = Xml.newPullParser();
19992            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19993            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19994                    new BlobXmlRestorer() {
19995                        @Override
19996                        public void apply(XmlPullParser parser, int userId)
19997                                throws XmlPullParserException, IOException {
19998                            synchronized (mPackages) {
19999                                mSettings.readPreferredActivitiesLPw(parser, userId);
20000                            }
20001                        }
20002                    } );
20003        } catch (Exception e) {
20004            if (DEBUG_BACKUP) {
20005                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20006            }
20007        }
20008    }
20009
20010    /**
20011     * Non-Binder method, support for the backup/restore mechanism: write the
20012     * default browser (etc) settings in its canonical XML format.  Returns the default
20013     * browser XML representation as a byte array, or null if there is none.
20014     */
20015    @Override
20016    public byte[] getDefaultAppsBackup(int userId) {
20017        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20018            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20019        }
20020
20021        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20022        try {
20023            final XmlSerializer serializer = new FastXmlSerializer();
20024            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20025            serializer.startDocument(null, true);
20026            serializer.startTag(null, TAG_DEFAULT_APPS);
20027
20028            synchronized (mPackages) {
20029                mSettings.writeDefaultAppsLPr(serializer, userId);
20030            }
20031
20032            serializer.endTag(null, TAG_DEFAULT_APPS);
20033            serializer.endDocument();
20034            serializer.flush();
20035        } catch (Exception e) {
20036            if (DEBUG_BACKUP) {
20037                Slog.e(TAG, "Unable to write default apps for backup", e);
20038            }
20039            return null;
20040        }
20041
20042        return dataStream.toByteArray();
20043    }
20044
20045    @Override
20046    public void restoreDefaultApps(byte[] backup, int userId) {
20047        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20048            throw new SecurityException("Only the system may call restoreDefaultApps()");
20049        }
20050
20051        try {
20052            final XmlPullParser parser = Xml.newPullParser();
20053            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20054            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20055                    new BlobXmlRestorer() {
20056                        @Override
20057                        public void apply(XmlPullParser parser, int userId)
20058                                throws XmlPullParserException, IOException {
20059                            synchronized (mPackages) {
20060                                mSettings.readDefaultAppsLPw(parser, userId);
20061                            }
20062                        }
20063                    } );
20064        } catch (Exception e) {
20065            if (DEBUG_BACKUP) {
20066                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20067            }
20068        }
20069    }
20070
20071    @Override
20072    public byte[] getIntentFilterVerificationBackup(int userId) {
20073        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20074            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20075        }
20076
20077        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20078        try {
20079            final XmlSerializer serializer = new FastXmlSerializer();
20080            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20081            serializer.startDocument(null, true);
20082            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20083
20084            synchronized (mPackages) {
20085                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20086            }
20087
20088            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20089            serializer.endDocument();
20090            serializer.flush();
20091        } catch (Exception e) {
20092            if (DEBUG_BACKUP) {
20093                Slog.e(TAG, "Unable to write default apps for backup", e);
20094            }
20095            return null;
20096        }
20097
20098        return dataStream.toByteArray();
20099    }
20100
20101    @Override
20102    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20103        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20104            throw new SecurityException("Only the system may call restorePreferredActivities()");
20105        }
20106
20107        try {
20108            final XmlPullParser parser = Xml.newPullParser();
20109            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20110            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20111                    new BlobXmlRestorer() {
20112                        @Override
20113                        public void apply(XmlPullParser parser, int userId)
20114                                throws XmlPullParserException, IOException {
20115                            synchronized (mPackages) {
20116                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20117                                mSettings.writeLPr();
20118                            }
20119                        }
20120                    } );
20121        } catch (Exception e) {
20122            if (DEBUG_BACKUP) {
20123                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20124            }
20125        }
20126    }
20127
20128    @Override
20129    public byte[] getPermissionGrantBackup(int userId) {
20130        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20131            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20132        }
20133
20134        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20135        try {
20136            final XmlSerializer serializer = new FastXmlSerializer();
20137            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20138            serializer.startDocument(null, true);
20139            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20140
20141            synchronized (mPackages) {
20142                serializeRuntimePermissionGrantsLPr(serializer, userId);
20143            }
20144
20145            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20146            serializer.endDocument();
20147            serializer.flush();
20148        } catch (Exception e) {
20149            if (DEBUG_BACKUP) {
20150                Slog.e(TAG, "Unable to write default apps for backup", e);
20151            }
20152            return null;
20153        }
20154
20155        return dataStream.toByteArray();
20156    }
20157
20158    @Override
20159    public void restorePermissionGrants(byte[] backup, int userId) {
20160        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20161            throw new SecurityException("Only the system may call restorePermissionGrants()");
20162        }
20163
20164        try {
20165            final XmlPullParser parser = Xml.newPullParser();
20166            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20167            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20168                    new BlobXmlRestorer() {
20169                        @Override
20170                        public void apply(XmlPullParser parser, int userId)
20171                                throws XmlPullParserException, IOException {
20172                            synchronized (mPackages) {
20173                                processRestoredPermissionGrantsLPr(parser, userId);
20174                            }
20175                        }
20176                    } );
20177        } catch (Exception e) {
20178            if (DEBUG_BACKUP) {
20179                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20180            }
20181        }
20182    }
20183
20184    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20185            throws IOException {
20186        serializer.startTag(null, TAG_ALL_GRANTS);
20187
20188        final int N = mSettings.mPackages.size();
20189        for (int i = 0; i < N; i++) {
20190            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20191            boolean pkgGrantsKnown = false;
20192
20193            PermissionsState packagePerms = ps.getPermissionsState();
20194
20195            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20196                final int grantFlags = state.getFlags();
20197                // only look at grants that are not system/policy fixed
20198                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20199                    final boolean isGranted = state.isGranted();
20200                    // And only back up the user-twiddled state bits
20201                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20202                        final String packageName = mSettings.mPackages.keyAt(i);
20203                        if (!pkgGrantsKnown) {
20204                            serializer.startTag(null, TAG_GRANT);
20205                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20206                            pkgGrantsKnown = true;
20207                        }
20208
20209                        final boolean userSet =
20210                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20211                        final boolean userFixed =
20212                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20213                        final boolean revoke =
20214                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20215
20216                        serializer.startTag(null, TAG_PERMISSION);
20217                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20218                        if (isGranted) {
20219                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20220                        }
20221                        if (userSet) {
20222                            serializer.attribute(null, ATTR_USER_SET, "true");
20223                        }
20224                        if (userFixed) {
20225                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20226                        }
20227                        if (revoke) {
20228                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20229                        }
20230                        serializer.endTag(null, TAG_PERMISSION);
20231                    }
20232                }
20233            }
20234
20235            if (pkgGrantsKnown) {
20236                serializer.endTag(null, TAG_GRANT);
20237            }
20238        }
20239
20240        serializer.endTag(null, TAG_ALL_GRANTS);
20241    }
20242
20243    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20244            throws XmlPullParserException, IOException {
20245        String pkgName = null;
20246        int outerDepth = parser.getDepth();
20247        int type;
20248        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20249                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20250            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20251                continue;
20252            }
20253
20254            final String tagName = parser.getName();
20255            if (tagName.equals(TAG_GRANT)) {
20256                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20257                if (DEBUG_BACKUP) {
20258                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20259                }
20260            } else if (tagName.equals(TAG_PERMISSION)) {
20261
20262                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20263                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20264
20265                int newFlagSet = 0;
20266                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20267                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20268                }
20269                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20270                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20271                }
20272                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20273                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20274                }
20275                if (DEBUG_BACKUP) {
20276                    Slog.v(TAG, "  + Restoring grant:"
20277                            + " pkg=" + pkgName
20278                            + " perm=" + permName
20279                            + " granted=" + isGranted
20280                            + " bits=0x" + Integer.toHexString(newFlagSet));
20281                }
20282                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20283                if (ps != null) {
20284                    // Already installed so we apply the grant immediately
20285                    if (DEBUG_BACKUP) {
20286                        Slog.v(TAG, "        + already installed; applying");
20287                    }
20288                    PermissionsState perms = ps.getPermissionsState();
20289                    BasePermission bp =
20290                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
20291                    if (bp != null) {
20292                        if (isGranted) {
20293                            perms.grantRuntimePermission(bp, userId);
20294                        }
20295                        if (newFlagSet != 0) {
20296                            perms.updatePermissionFlags(
20297                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20298                        }
20299                    }
20300                } else {
20301                    // Need to wait for post-restore install to apply the grant
20302                    if (DEBUG_BACKUP) {
20303                        Slog.v(TAG, "        - not yet installed; saving for later");
20304                    }
20305                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20306                            isGranted, newFlagSet, userId);
20307                }
20308            } else {
20309                PackageManagerService.reportSettingsProblem(Log.WARN,
20310                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20311                XmlUtils.skipCurrentTag(parser);
20312            }
20313        }
20314
20315        scheduleWriteSettingsLocked();
20316        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20317    }
20318
20319    @Override
20320    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20321            int sourceUserId, int targetUserId, int flags) {
20322        mContext.enforceCallingOrSelfPermission(
20323                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20324        int callingUid = Binder.getCallingUid();
20325        enforceOwnerRights(ownerPackage, callingUid);
20326        PackageManagerServiceUtils.enforceShellRestriction(
20327                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20328        if (intentFilter.countActions() == 0) {
20329            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20330            return;
20331        }
20332        synchronized (mPackages) {
20333            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20334                    ownerPackage, targetUserId, flags);
20335            CrossProfileIntentResolver resolver =
20336                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20337            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20338            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20339            if (existing != null) {
20340                int size = existing.size();
20341                for (int i = 0; i < size; i++) {
20342                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20343                        return;
20344                    }
20345                }
20346            }
20347            resolver.addFilter(newFilter);
20348            scheduleWritePackageRestrictionsLocked(sourceUserId);
20349        }
20350    }
20351
20352    @Override
20353    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20354        mContext.enforceCallingOrSelfPermission(
20355                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20356        final int callingUid = Binder.getCallingUid();
20357        enforceOwnerRights(ownerPackage, callingUid);
20358        PackageManagerServiceUtils.enforceShellRestriction(
20359                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20360        synchronized (mPackages) {
20361            CrossProfileIntentResolver resolver =
20362                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20363            ArraySet<CrossProfileIntentFilter> set =
20364                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20365            for (CrossProfileIntentFilter filter : set) {
20366                if (filter.getOwnerPackage().equals(ownerPackage)) {
20367                    resolver.removeFilter(filter);
20368                }
20369            }
20370            scheduleWritePackageRestrictionsLocked(sourceUserId);
20371        }
20372    }
20373
20374    // Enforcing that callingUid is owning pkg on userId
20375    private void enforceOwnerRights(String pkg, int callingUid) {
20376        // The system owns everything.
20377        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20378            return;
20379        }
20380        final int callingUserId = UserHandle.getUserId(callingUid);
20381        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20382        if (pi == null) {
20383            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20384                    + callingUserId);
20385        }
20386        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20387            throw new SecurityException("Calling uid " + callingUid
20388                    + " does not own package " + pkg);
20389        }
20390    }
20391
20392    @Override
20393    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20394        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20395            return null;
20396        }
20397        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20398    }
20399
20400    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20401        UserManagerService ums = UserManagerService.getInstance();
20402        if (ums != null) {
20403            final UserInfo parent = ums.getProfileParent(userId);
20404            final int launcherUid = (parent != null) ? parent.id : userId;
20405            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20406            if (launcherComponent != null) {
20407                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20408                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20409                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20410                        .setPackage(launcherComponent.getPackageName());
20411                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20412            }
20413        }
20414    }
20415
20416    /**
20417     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20418     * then reports the most likely home activity or null if there are more than one.
20419     */
20420    private ComponentName getDefaultHomeActivity(int userId) {
20421        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20422        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20423        if (cn != null) {
20424            return cn;
20425        }
20426
20427        // Find the launcher with the highest priority and return that component if there are no
20428        // other home activity with the same priority.
20429        int lastPriority = Integer.MIN_VALUE;
20430        ComponentName lastComponent = null;
20431        final int size = allHomeCandidates.size();
20432        for (int i = 0; i < size; i++) {
20433            final ResolveInfo ri = allHomeCandidates.get(i);
20434            if (ri.priority > lastPriority) {
20435                lastComponent = ri.activityInfo.getComponentName();
20436                lastPriority = ri.priority;
20437            } else if (ri.priority == lastPriority) {
20438                // Two components found with same priority.
20439                lastComponent = null;
20440            }
20441        }
20442        return lastComponent;
20443    }
20444
20445    private Intent getHomeIntent() {
20446        Intent intent = new Intent(Intent.ACTION_MAIN);
20447        intent.addCategory(Intent.CATEGORY_HOME);
20448        intent.addCategory(Intent.CATEGORY_DEFAULT);
20449        return intent;
20450    }
20451
20452    private IntentFilter getHomeFilter() {
20453        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20454        filter.addCategory(Intent.CATEGORY_HOME);
20455        filter.addCategory(Intent.CATEGORY_DEFAULT);
20456        return filter;
20457    }
20458
20459    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20460            int userId) {
20461        Intent intent  = getHomeIntent();
20462        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20463                PackageManager.GET_META_DATA, userId);
20464        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20465                true, false, false, userId);
20466
20467        allHomeCandidates.clear();
20468        if (list != null) {
20469            for (ResolveInfo ri : list) {
20470                allHomeCandidates.add(ri);
20471            }
20472        }
20473        return (preferred == null || preferred.activityInfo == null)
20474                ? null
20475                : new ComponentName(preferred.activityInfo.packageName,
20476                        preferred.activityInfo.name);
20477    }
20478
20479    @Override
20480    public void setHomeActivity(ComponentName comp, int userId) {
20481        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20482            return;
20483        }
20484        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20485        getHomeActivitiesAsUser(homeActivities, userId);
20486
20487        boolean found = false;
20488
20489        final int size = homeActivities.size();
20490        final ComponentName[] set = new ComponentName[size];
20491        for (int i = 0; i < size; i++) {
20492            final ResolveInfo candidate = homeActivities.get(i);
20493            final ActivityInfo info = candidate.activityInfo;
20494            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20495            set[i] = activityName;
20496            if (!found && activityName.equals(comp)) {
20497                found = true;
20498            }
20499        }
20500        if (!found) {
20501            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20502                    + userId);
20503        }
20504        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20505                set, comp, userId);
20506    }
20507
20508    private @Nullable String getSetupWizardPackageName() {
20509        final Intent intent = new Intent(Intent.ACTION_MAIN);
20510        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20511
20512        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20513                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20514                        | MATCH_DISABLED_COMPONENTS,
20515                UserHandle.myUserId());
20516        if (matches.size() == 1) {
20517            return matches.get(0).getComponentInfo().packageName;
20518        } else {
20519            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20520                    + ": matches=" + matches);
20521            return null;
20522        }
20523    }
20524
20525    private @Nullable String getStorageManagerPackageName() {
20526        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20527
20528        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20529                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20530                        | MATCH_DISABLED_COMPONENTS,
20531                UserHandle.myUserId());
20532        if (matches.size() == 1) {
20533            return matches.get(0).getComponentInfo().packageName;
20534        } else {
20535            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20536                    + matches.size() + ": matches=" + matches);
20537            return null;
20538        }
20539    }
20540
20541    @Override
20542    public String getSystemTextClassifierPackageName() {
20543        return mContext.getString(R.string.config_defaultTextClassifierPackage);
20544    }
20545
20546    @Override
20547    public void setApplicationEnabledSetting(String appPackageName,
20548            int newState, int flags, int userId, String callingPackage) {
20549        if (!sUserManager.exists(userId)) return;
20550        if (callingPackage == null) {
20551            callingPackage = Integer.toString(Binder.getCallingUid());
20552        }
20553        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20554    }
20555
20556    @Override
20557    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20558        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20559        synchronized (mPackages) {
20560            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20561            if (pkgSetting != null) {
20562                pkgSetting.setUpdateAvailable(updateAvailable);
20563            }
20564        }
20565    }
20566
20567    @Override
20568    public void setComponentEnabledSetting(ComponentName componentName,
20569            int newState, int flags, int userId) {
20570        if (!sUserManager.exists(userId)) return;
20571        setEnabledSetting(componentName.getPackageName(),
20572                componentName.getClassName(), newState, flags, userId, null);
20573    }
20574
20575    private void setEnabledSetting(final String packageName, String className, int newState,
20576            final int flags, int userId, String callingPackage) {
20577        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20578              || newState == COMPONENT_ENABLED_STATE_ENABLED
20579              || newState == COMPONENT_ENABLED_STATE_DISABLED
20580              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20581              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20582            throw new IllegalArgumentException("Invalid new component state: "
20583                    + newState);
20584        }
20585        PackageSetting pkgSetting;
20586        final int callingUid = Binder.getCallingUid();
20587        final int permission;
20588        if (callingUid == Process.SYSTEM_UID) {
20589            permission = PackageManager.PERMISSION_GRANTED;
20590        } else {
20591            permission = mContext.checkCallingOrSelfPermission(
20592                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20593        }
20594        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20595                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20596        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20597        boolean sendNow = false;
20598        boolean isApp = (className == null);
20599        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20600        String componentName = isApp ? packageName : className;
20601        int packageUid = -1;
20602        ArrayList<String> components;
20603
20604        // reader
20605        synchronized (mPackages) {
20606            pkgSetting = mSettings.mPackages.get(packageName);
20607            if (pkgSetting == null) {
20608                if (!isCallerInstantApp) {
20609                    if (className == null) {
20610                        throw new IllegalArgumentException("Unknown package: " + packageName);
20611                    }
20612                    throw new IllegalArgumentException(
20613                            "Unknown component: " + packageName + "/" + className);
20614                } else {
20615                    // throw SecurityException to prevent leaking package information
20616                    throw new SecurityException(
20617                            "Attempt to change component state; "
20618                            + "pid=" + Binder.getCallingPid()
20619                            + ", uid=" + callingUid
20620                            + (className == null
20621                                    ? ", package=" + packageName
20622                                    : ", component=" + packageName + "/" + className));
20623                }
20624            }
20625        }
20626
20627        // Limit who can change which apps
20628        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20629            // Don't allow apps that don't have permission to modify other apps
20630            if (!allowedByPermission
20631                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20632                throw new SecurityException(
20633                        "Attempt to change component state; "
20634                        + "pid=" + Binder.getCallingPid()
20635                        + ", uid=" + callingUid
20636                        + (className == null
20637                                ? ", package=" + packageName
20638                                : ", component=" + packageName + "/" + className));
20639            }
20640            // Don't allow changing protected packages.
20641            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20642                throw new SecurityException("Cannot disable a protected package: " + packageName);
20643            }
20644        }
20645
20646        synchronized (mPackages) {
20647            if (callingUid == Process.SHELL_UID
20648                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20649                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20650                // unless it is a test package.
20651                int oldState = pkgSetting.getEnabled(userId);
20652                if (className == null
20653                        &&
20654                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20655                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20656                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20657                        &&
20658                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20659                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20660                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20661                    // ok
20662                } else {
20663                    throw new SecurityException(
20664                            "Shell cannot change component state for " + packageName + "/"
20665                                    + className + " to " + newState);
20666                }
20667            }
20668        }
20669        if (className == null) {
20670            // We're dealing with an application/package level state change
20671            synchronized (mPackages) {
20672                if (pkgSetting.getEnabled(userId) == newState) {
20673                    // Nothing to do
20674                    return;
20675                }
20676            }
20677            // If we're enabling a system stub, there's a little more work to do.
20678            // Prior to enabling the package, we need to decompress the APK(s) to the
20679            // data partition and then replace the version on the system partition.
20680            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20681            final boolean isSystemStub = deletedPkg.isStub
20682                    && deletedPkg.isSystem();
20683            if (isSystemStub
20684                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20685                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20686                final File codePath = decompressPackage(deletedPkg);
20687                if (codePath == null) {
20688                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20689                    return;
20690                }
20691                // TODO remove direct parsing of the package object during internal cleanup
20692                // of scan package
20693                // We need to call parse directly here for no other reason than we need
20694                // the new package in order to disable the old one [we use the information
20695                // for some internal optimization to optionally create a new package setting
20696                // object on replace]. However, we can't get the package from the scan
20697                // because the scan modifies live structures and we need to remove the
20698                // old [system] package from the system before a scan can be attempted.
20699                // Once scan is indempotent we can remove this parse and use the package
20700                // object we scanned, prior to adding it to package settings.
20701                final PackageParser pp = new PackageParser();
20702                pp.setSeparateProcesses(mSeparateProcesses);
20703                pp.setDisplayMetrics(mMetrics);
20704                pp.setCallback(mPackageParserCallback);
20705                final PackageParser.Package tmpPkg;
20706                try {
20707                    final @ParseFlags int parseFlags = mDefParseFlags
20708                            | PackageParser.PARSE_MUST_BE_APK
20709                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20710                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20711                } catch (PackageParserException e) {
20712                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20713                    return;
20714                }
20715                synchronized (mInstallLock) {
20716                    // Disable the stub and remove any package entries
20717                    removePackageLI(deletedPkg, true);
20718                    synchronized (mPackages) {
20719                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20720                    }
20721                    final PackageParser.Package pkg;
20722                    try (PackageFreezer freezer =
20723                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20724                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20725                                | PackageParser.PARSE_ENFORCE_CODE;
20726                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20727                                0 /*currentTime*/, null /*user*/);
20728                        prepareAppDataAfterInstallLIF(pkg);
20729                        synchronized (mPackages) {
20730                            try {
20731                                updateSharedLibrariesLPr(pkg, null);
20732                            } catch (PackageManagerException e) {
20733                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20734                            }
20735                            mPermissionManager.updatePermissions(
20736                                    pkg.packageName, pkg, true, mPackages.values(),
20737                                    mPermissionCallback);
20738                            mSettings.writeLPr();
20739                        }
20740                    } catch (PackageManagerException e) {
20741                        // Whoops! Something went wrong; try to roll back to the stub
20742                        Slog.w(TAG, "Failed to install compressed system package:"
20743                                + pkgSetting.name, e);
20744                        // Remove the failed install
20745                        removeCodePathLI(codePath);
20746
20747                        // Install the system package
20748                        try (PackageFreezer freezer =
20749                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20750                            synchronized (mPackages) {
20751                                // NOTE: The system package always needs to be enabled; even
20752                                // if it's for a compressed stub. If we don't, installing the
20753                                // system package fails during scan [scanning checks the disabled
20754                                // packages]. We will reverse this later, after we've "installed"
20755                                // the stub.
20756                                // This leaves us in a fragile state; the stub should never be
20757                                // enabled, so, cross your fingers and hope nothing goes wrong
20758                                // until we can disable the package later.
20759                                enableSystemPackageLPw(deletedPkg);
20760                            }
20761                            installPackageFromSystemLIF(deletedPkg.codePath,
20762                                    false /*isPrivileged*/, null /*allUserHandles*/,
20763                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20764                                    true /*writeSettings*/);
20765                        } catch (PackageManagerException pme) {
20766                            Slog.w(TAG, "Failed to restore system package:"
20767                                    + deletedPkg.packageName, pme);
20768                        } finally {
20769                            synchronized (mPackages) {
20770                                mSettings.disableSystemPackageLPw(
20771                                        deletedPkg.packageName, true /*replaced*/);
20772                                mSettings.writeLPr();
20773                            }
20774                        }
20775                        return;
20776                    }
20777                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20778                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20779                    mDexManager.notifyPackageUpdated(pkg.packageName,
20780                            pkg.baseCodePath, pkg.splitCodePaths);
20781                }
20782            }
20783            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20784                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20785                // Don't care about who enables an app.
20786                callingPackage = null;
20787            }
20788            synchronized (mPackages) {
20789                pkgSetting.setEnabled(newState, userId, callingPackage);
20790            }
20791        } else {
20792            synchronized (mPackages) {
20793                // We're dealing with a component level state change
20794                // First, verify that this is a valid class name.
20795                PackageParser.Package pkg = pkgSetting.pkg;
20796                if (pkg == null || !pkg.hasComponentClassName(className)) {
20797                    if (pkg != null &&
20798                            pkg.applicationInfo.targetSdkVersion >=
20799                                    Build.VERSION_CODES.JELLY_BEAN) {
20800                        throw new IllegalArgumentException("Component class " + className
20801                                + " does not exist in " + packageName);
20802                    } else {
20803                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20804                                + className + " does not exist in " + packageName);
20805                    }
20806                }
20807                switch (newState) {
20808                    case COMPONENT_ENABLED_STATE_ENABLED:
20809                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20810                            return;
20811                        }
20812                        break;
20813                    case COMPONENT_ENABLED_STATE_DISABLED:
20814                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20815                            return;
20816                        }
20817                        break;
20818                    case COMPONENT_ENABLED_STATE_DEFAULT:
20819                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20820                            return;
20821                        }
20822                        break;
20823                    default:
20824                        Slog.e(TAG, "Invalid new component state: " + newState);
20825                        return;
20826                }
20827            }
20828        }
20829        synchronized (mPackages) {
20830            scheduleWritePackageRestrictionsLocked(userId);
20831            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20832            final long callingId = Binder.clearCallingIdentity();
20833            try {
20834                updateInstantAppInstallerLocked(packageName);
20835            } finally {
20836                Binder.restoreCallingIdentity(callingId);
20837            }
20838            components = mPendingBroadcasts.get(userId, packageName);
20839            final boolean newPackage = components == null;
20840            if (newPackage) {
20841                components = new ArrayList<String>();
20842            }
20843            if (!components.contains(componentName)) {
20844                components.add(componentName);
20845            }
20846            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20847                sendNow = true;
20848                // Purge entry from pending broadcast list if another one exists already
20849                // since we are sending one right away.
20850                mPendingBroadcasts.remove(userId, packageName);
20851            } else {
20852                if (newPackage) {
20853                    mPendingBroadcasts.put(userId, packageName, components);
20854                }
20855                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20856                    // Schedule a message
20857                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20858                }
20859            }
20860        }
20861
20862        long callingId = Binder.clearCallingIdentity();
20863        try {
20864            if (sendNow) {
20865                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20866                sendPackageChangedBroadcast(packageName,
20867                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20868            }
20869        } finally {
20870            Binder.restoreCallingIdentity(callingId);
20871        }
20872    }
20873
20874    @Override
20875    public void flushPackageRestrictionsAsUser(int userId) {
20876        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20877            return;
20878        }
20879        if (!sUserManager.exists(userId)) {
20880            return;
20881        }
20882        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20883                false /* checkShell */, "flushPackageRestrictions");
20884        synchronized (mPackages) {
20885            mSettings.writePackageRestrictionsLPr(userId);
20886            mDirtyUsers.remove(userId);
20887            if (mDirtyUsers.isEmpty()) {
20888                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20889            }
20890        }
20891    }
20892
20893    private void sendPackageChangedBroadcast(String packageName,
20894            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20895        if (DEBUG_INSTALL)
20896            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20897                    + componentNames);
20898        Bundle extras = new Bundle(4);
20899        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20900        String nameList[] = new String[componentNames.size()];
20901        componentNames.toArray(nameList);
20902        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20903        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20904        extras.putInt(Intent.EXTRA_UID, packageUid);
20905        // If this is not reporting a change of the overall package, then only send it
20906        // to registered receivers.  We don't want to launch a swath of apps for every
20907        // little component state change.
20908        final int flags = !componentNames.contains(packageName)
20909                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20910        final int userId = UserHandle.getUserId(packageUid);
20911        final boolean isInstantApp = isInstantApp(packageName, userId);
20912        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20913        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20914        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20915                userIds, instantUserIds);
20916    }
20917
20918    @Override
20919    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20920        if (!sUserManager.exists(userId)) return;
20921        final int callingUid = Binder.getCallingUid();
20922        if (getInstantAppPackageName(callingUid) != null) {
20923            return;
20924        }
20925        final int permission = mContext.checkCallingOrSelfPermission(
20926                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20927        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20928        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20929                true /* requireFullPermission */, true /* checkShell */, "stop package");
20930        // writer
20931        synchronized (mPackages) {
20932            final PackageSetting ps = mSettings.mPackages.get(packageName);
20933            if (!filterAppAccessLPr(ps, callingUid, userId)
20934                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20935                            allowedByPermission, callingUid, userId)) {
20936                scheduleWritePackageRestrictionsLocked(userId);
20937            }
20938        }
20939    }
20940
20941    @Override
20942    public String getInstallerPackageName(String packageName) {
20943        final int callingUid = Binder.getCallingUid();
20944        synchronized (mPackages) {
20945            final PackageSetting ps = mSettings.mPackages.get(packageName);
20946            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20947                return null;
20948            }
20949            return mSettings.getInstallerPackageNameLPr(packageName);
20950        }
20951    }
20952
20953    public boolean isOrphaned(String packageName) {
20954        // reader
20955        synchronized (mPackages) {
20956            return mSettings.isOrphaned(packageName);
20957        }
20958    }
20959
20960    @Override
20961    public int getApplicationEnabledSetting(String packageName, int userId) {
20962        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20963        int callingUid = Binder.getCallingUid();
20964        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20965                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20966        // reader
20967        synchronized (mPackages) {
20968            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20969                return COMPONENT_ENABLED_STATE_DISABLED;
20970            }
20971            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20972        }
20973    }
20974
20975    @Override
20976    public int getComponentEnabledSetting(ComponentName component, int userId) {
20977        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20978        int callingUid = Binder.getCallingUid();
20979        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20980                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20981        synchronized (mPackages) {
20982            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20983                    component, TYPE_UNKNOWN, userId)) {
20984                return COMPONENT_ENABLED_STATE_DISABLED;
20985            }
20986            return mSettings.getComponentEnabledSettingLPr(component, userId);
20987        }
20988    }
20989
20990    @Override
20991    public void enterSafeMode() {
20992        enforceSystemOrRoot("Only the system can request entering safe mode");
20993
20994        if (!mSystemReady) {
20995            mSafeMode = true;
20996        }
20997    }
20998
20999    @Override
21000    public void systemReady() {
21001        enforceSystemOrRoot("Only the system can claim the system is ready");
21002
21003        mSystemReady = true;
21004        final ContentResolver resolver = mContext.getContentResolver();
21005        ContentObserver co = new ContentObserver(mHandler) {
21006            @Override
21007            public void onChange(boolean selfChange) {
21008                mWebInstantAppsDisabled =
21009                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21010                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21011            }
21012        };
21013        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21014                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21015                false, co, UserHandle.USER_SYSTEM);
21016        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure
21017                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21018        co.onChange(true);
21019
21020        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21021        // disabled after already being started.
21022        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21023                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21024
21025        // Read the compatibilty setting when the system is ready.
21026        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21027                mContext.getContentResolver(),
21028                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21029        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21030        if (DEBUG_SETTINGS) {
21031            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21032        }
21033
21034        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21035
21036        synchronized (mPackages) {
21037            // Verify that all of the preferred activity components actually
21038            // exist.  It is possible for applications to be updated and at
21039            // that point remove a previously declared activity component that
21040            // had been set as a preferred activity.  We try to clean this up
21041            // the next time we encounter that preferred activity, but it is
21042            // possible for the user flow to never be able to return to that
21043            // situation so here we do a sanity check to make sure we haven't
21044            // left any junk around.
21045            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21046            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21047                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21048                removed.clear();
21049                for (PreferredActivity pa : pir.filterSet()) {
21050                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21051                        removed.add(pa);
21052                    }
21053                }
21054                if (removed.size() > 0) {
21055                    for (int r=0; r<removed.size(); r++) {
21056                        PreferredActivity pa = removed.get(r);
21057                        Slog.w(TAG, "Removing dangling preferred activity: "
21058                                + pa.mPref.mComponent);
21059                        pir.removeFilter(pa);
21060                    }
21061                    mSettings.writePackageRestrictionsLPr(
21062                            mSettings.mPreferredActivities.keyAt(i));
21063                }
21064            }
21065
21066            for (int userId : UserManagerService.getInstance().getUserIds()) {
21067                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21068                    grantPermissionsUserIds = ArrayUtils.appendInt(
21069                            grantPermissionsUserIds, userId);
21070                }
21071            }
21072        }
21073        sUserManager.systemReady();
21074        // If we upgraded grant all default permissions before kicking off.
21075        for (int userId : grantPermissionsUserIds) {
21076            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21077        }
21078
21079        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21080            // If we did not grant default permissions, we preload from this the
21081            // default permission exceptions lazily to ensure we don't hit the
21082            // disk on a new user creation.
21083            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21084        }
21085
21086        // Now that we've scanned all packages, and granted any default
21087        // permissions, ensure permissions are updated. Beware of dragons if you
21088        // try optimizing this.
21089        synchronized (mPackages) {
21090            mPermissionManager.updateAllPermissions(
21091                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
21092                    mPermissionCallback);
21093        }
21094
21095        // Kick off any messages waiting for system ready
21096        if (mPostSystemReadyMessages != null) {
21097            for (Message msg : mPostSystemReadyMessages) {
21098                msg.sendToTarget();
21099            }
21100            mPostSystemReadyMessages = null;
21101        }
21102
21103        // Watch for external volumes that come and go over time
21104        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21105        storage.registerListener(mStorageListener);
21106
21107        mInstallerService.systemReady();
21108        mDexManager.systemReady();
21109        mPackageDexOptimizer.systemReady();
21110
21111        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21112                StorageManagerInternal.class);
21113        StorageManagerInternal.addExternalStoragePolicy(
21114                new StorageManagerInternal.ExternalStorageMountPolicy() {
21115            @Override
21116            public int getMountMode(int uid, String packageName) {
21117                if (Process.isIsolated(uid)) {
21118                    return Zygote.MOUNT_EXTERNAL_NONE;
21119                }
21120                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21121                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21122                }
21123                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21124                    return Zygote.MOUNT_EXTERNAL_READ;
21125                }
21126                return Zygote.MOUNT_EXTERNAL_WRITE;
21127            }
21128
21129            @Override
21130            public boolean hasExternalStorage(int uid, String packageName) {
21131                return true;
21132            }
21133        });
21134
21135        // Now that we're mostly running, clean up stale users and apps
21136        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21137        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21138
21139        mPermissionManager.systemReady();
21140
21141        if (mInstantAppResolverConnection != null) {
21142            mContext.registerReceiver(new BroadcastReceiver() {
21143                @Override
21144                public void onReceive(Context context, Intent intent) {
21145                    mInstantAppResolverConnection.optimisticBind();
21146                    mContext.unregisterReceiver(this);
21147                }
21148            }, new IntentFilter(Intent.ACTION_BOOT_COMPLETED));
21149        }
21150    }
21151
21152    public void waitForAppDataPrepared() {
21153        if (mPrepareAppDataFuture == null) {
21154            return;
21155        }
21156        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21157        mPrepareAppDataFuture = null;
21158    }
21159
21160    @Override
21161    public boolean isSafeMode() {
21162        // allow instant applications
21163        return mSafeMode;
21164    }
21165
21166    @Override
21167    public boolean hasSystemUidErrors() {
21168        // allow instant applications
21169        return mHasSystemUidErrors;
21170    }
21171
21172    static String arrayToString(int[] array) {
21173        StringBuffer buf = new StringBuffer(128);
21174        buf.append('[');
21175        if (array != null) {
21176            for (int i=0; i<array.length; i++) {
21177                if (i > 0) buf.append(", ");
21178                buf.append(array[i]);
21179            }
21180        }
21181        buf.append(']');
21182        return buf.toString();
21183    }
21184
21185    @Override
21186    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21187            FileDescriptor err, String[] args, ShellCallback callback,
21188            ResultReceiver resultReceiver) {
21189        (new PackageManagerShellCommand(this)).exec(
21190                this, in, out, err, args, callback, resultReceiver);
21191    }
21192
21193    @Override
21194    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21195        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21196
21197        DumpState dumpState = new DumpState();
21198        boolean fullPreferred = false;
21199        boolean checkin = false;
21200
21201        String packageName = null;
21202        ArraySet<String> permissionNames = null;
21203
21204        int opti = 0;
21205        while (opti < args.length) {
21206            String opt = args[opti];
21207            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21208                break;
21209            }
21210            opti++;
21211
21212            if ("-a".equals(opt)) {
21213                // Right now we only know how to print all.
21214            } else if ("-h".equals(opt)) {
21215                pw.println("Package manager dump options:");
21216                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21217                pw.println("    --checkin: dump for a checkin");
21218                pw.println("    -f: print details of intent filters");
21219                pw.println("    -h: print this help");
21220                pw.println("  cmd may be one of:");
21221                pw.println("    l[ibraries]: list known shared libraries");
21222                pw.println("    f[eatures]: list device features");
21223                pw.println("    k[eysets]: print known keysets");
21224                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21225                pw.println("    perm[issions]: dump permissions");
21226                pw.println("    permission [name ...]: dump declaration and use of given permission");
21227                pw.println("    pref[erred]: print preferred package settings");
21228                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21229                pw.println("    prov[iders]: dump content providers");
21230                pw.println("    p[ackages]: dump installed packages");
21231                pw.println("    s[hared-users]: dump shared user IDs");
21232                pw.println("    m[essages]: print collected runtime messages");
21233                pw.println("    v[erifiers]: print package verifier info");
21234                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21235                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21236                pw.println("    version: print database version info");
21237                pw.println("    write: write current settings now");
21238                pw.println("    installs: details about install sessions");
21239                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21240                pw.println("    dexopt: dump dexopt state");
21241                pw.println("    compiler-stats: dump compiler statistics");
21242                pw.println("    service-permissions: dump permissions required by services");
21243                pw.println("    <package.name>: info about given package");
21244                return;
21245            } else if ("--checkin".equals(opt)) {
21246                checkin = true;
21247            } else if ("-f".equals(opt)) {
21248                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21249            } else if ("--proto".equals(opt)) {
21250                dumpProto(fd);
21251                return;
21252            } else {
21253                pw.println("Unknown argument: " + opt + "; use -h for help");
21254            }
21255        }
21256
21257        // Is the caller requesting to dump a particular piece of data?
21258        if (opti < args.length) {
21259            String cmd = args[opti];
21260            opti++;
21261            // Is this a package name?
21262            if ("android".equals(cmd) || cmd.contains(".")) {
21263                packageName = cmd;
21264                // When dumping a single package, we always dump all of its
21265                // filter information since the amount of data will be reasonable.
21266                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21267            } else if ("check-permission".equals(cmd)) {
21268                if (opti >= args.length) {
21269                    pw.println("Error: check-permission missing permission argument");
21270                    return;
21271                }
21272                String perm = args[opti];
21273                opti++;
21274                if (opti >= args.length) {
21275                    pw.println("Error: check-permission missing package argument");
21276                    return;
21277                }
21278
21279                String pkg = args[opti];
21280                opti++;
21281                int user = UserHandle.getUserId(Binder.getCallingUid());
21282                if (opti < args.length) {
21283                    try {
21284                        user = Integer.parseInt(args[opti]);
21285                    } catch (NumberFormatException e) {
21286                        pw.println("Error: check-permission user argument is not a number: "
21287                                + args[opti]);
21288                        return;
21289                    }
21290                }
21291
21292                // Normalize package name to handle renamed packages and static libs
21293                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21294
21295                pw.println(checkPermission(perm, pkg, user));
21296                return;
21297            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21298                dumpState.setDump(DumpState.DUMP_LIBS);
21299            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21300                dumpState.setDump(DumpState.DUMP_FEATURES);
21301            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21302                if (opti >= args.length) {
21303                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21304                            | DumpState.DUMP_SERVICE_RESOLVERS
21305                            | DumpState.DUMP_RECEIVER_RESOLVERS
21306                            | DumpState.DUMP_CONTENT_RESOLVERS);
21307                } else {
21308                    while (opti < args.length) {
21309                        String name = args[opti];
21310                        if ("a".equals(name) || "activity".equals(name)) {
21311                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21312                        } else if ("s".equals(name) || "service".equals(name)) {
21313                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21314                        } else if ("r".equals(name) || "receiver".equals(name)) {
21315                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21316                        } else if ("c".equals(name) || "content".equals(name)) {
21317                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21318                        } else {
21319                            pw.println("Error: unknown resolver table type: " + name);
21320                            return;
21321                        }
21322                        opti++;
21323                    }
21324                }
21325            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21326                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21327            } else if ("permission".equals(cmd)) {
21328                if (opti >= args.length) {
21329                    pw.println("Error: permission requires permission name");
21330                    return;
21331                }
21332                permissionNames = new ArraySet<>();
21333                while (opti < args.length) {
21334                    permissionNames.add(args[opti]);
21335                    opti++;
21336                }
21337                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21338                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21339            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21340                dumpState.setDump(DumpState.DUMP_PREFERRED);
21341            } else if ("preferred-xml".equals(cmd)) {
21342                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21343                if (opti < args.length && "--full".equals(args[opti])) {
21344                    fullPreferred = true;
21345                    opti++;
21346                }
21347            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21348                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21349            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21350                dumpState.setDump(DumpState.DUMP_PACKAGES);
21351            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21352                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21353            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21354                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21355            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21356                dumpState.setDump(DumpState.DUMP_MESSAGES);
21357            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21358                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21359            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21360                    || "intent-filter-verifiers".equals(cmd)) {
21361                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21362            } else if ("version".equals(cmd)) {
21363                dumpState.setDump(DumpState.DUMP_VERSION);
21364            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21365                dumpState.setDump(DumpState.DUMP_KEYSETS);
21366            } else if ("installs".equals(cmd)) {
21367                dumpState.setDump(DumpState.DUMP_INSTALLS);
21368            } else if ("frozen".equals(cmd)) {
21369                dumpState.setDump(DumpState.DUMP_FROZEN);
21370            } else if ("volumes".equals(cmd)) {
21371                dumpState.setDump(DumpState.DUMP_VOLUMES);
21372            } else if ("dexopt".equals(cmd)) {
21373                dumpState.setDump(DumpState.DUMP_DEXOPT);
21374            } else if ("compiler-stats".equals(cmd)) {
21375                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21376            } else if ("changes".equals(cmd)) {
21377                dumpState.setDump(DumpState.DUMP_CHANGES);
21378            } else if ("service-permissions".equals(cmd)) {
21379                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
21380            } else if ("write".equals(cmd)) {
21381                synchronized (mPackages) {
21382                    mSettings.writeLPr();
21383                    pw.println("Settings written.");
21384                    return;
21385                }
21386            }
21387        }
21388
21389        if (checkin) {
21390            pw.println("vers,1");
21391        }
21392
21393        // reader
21394        synchronized (mPackages) {
21395            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21396                if (!checkin) {
21397                    if (dumpState.onTitlePrinted())
21398                        pw.println();
21399                    pw.println("Database versions:");
21400                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21401                }
21402            }
21403
21404            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21405                if (!checkin) {
21406                    if (dumpState.onTitlePrinted())
21407                        pw.println();
21408                    pw.println("Verifiers:");
21409                    pw.print("  Required: ");
21410                    pw.print(mRequiredVerifierPackage);
21411                    pw.print(" (uid=");
21412                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21413                            UserHandle.USER_SYSTEM));
21414                    pw.println(")");
21415                } else if (mRequiredVerifierPackage != null) {
21416                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21417                    pw.print(",");
21418                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21419                            UserHandle.USER_SYSTEM));
21420                }
21421            }
21422
21423            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21424                    packageName == null) {
21425                if (mIntentFilterVerifierComponent != null) {
21426                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21427                    if (!checkin) {
21428                        if (dumpState.onTitlePrinted())
21429                            pw.println();
21430                        pw.println("Intent Filter Verifier:");
21431                        pw.print("  Using: ");
21432                        pw.print(verifierPackageName);
21433                        pw.print(" (uid=");
21434                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21435                                UserHandle.USER_SYSTEM));
21436                        pw.println(")");
21437                    } else if (verifierPackageName != null) {
21438                        pw.print("ifv,"); pw.print(verifierPackageName);
21439                        pw.print(",");
21440                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21441                                UserHandle.USER_SYSTEM));
21442                    }
21443                } else {
21444                    pw.println();
21445                    pw.println("No Intent Filter Verifier available!");
21446                }
21447            }
21448
21449            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21450                boolean printedHeader = false;
21451                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21452                while (it.hasNext()) {
21453                    String libName = it.next();
21454                    LongSparseArray<SharedLibraryEntry> versionedLib
21455                            = mSharedLibraries.get(libName);
21456                    if (versionedLib == null) {
21457                        continue;
21458                    }
21459                    final int versionCount = versionedLib.size();
21460                    for (int i = 0; i < versionCount; i++) {
21461                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21462                        if (!checkin) {
21463                            if (!printedHeader) {
21464                                if (dumpState.onTitlePrinted())
21465                                    pw.println();
21466                                pw.println("Libraries:");
21467                                printedHeader = true;
21468                            }
21469                            pw.print("  ");
21470                        } else {
21471                            pw.print("lib,");
21472                        }
21473                        pw.print(libEntry.info.getName());
21474                        if (libEntry.info.isStatic()) {
21475                            pw.print(" version=" + libEntry.info.getLongVersion());
21476                        }
21477                        if (!checkin) {
21478                            pw.print(" -> ");
21479                        }
21480                        if (libEntry.path != null) {
21481                            pw.print(" (jar) ");
21482                            pw.print(libEntry.path);
21483                        } else {
21484                            pw.print(" (apk) ");
21485                            pw.print(libEntry.apk);
21486                        }
21487                        pw.println();
21488                    }
21489                }
21490            }
21491
21492            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21493                if (dumpState.onTitlePrinted())
21494                    pw.println();
21495                if (!checkin) {
21496                    pw.println("Features:");
21497                }
21498
21499                synchronized (mAvailableFeatures) {
21500                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21501                        if (checkin) {
21502                            pw.print("feat,");
21503                            pw.print(feat.name);
21504                            pw.print(",");
21505                            pw.println(feat.version);
21506                        } else {
21507                            pw.print("  ");
21508                            pw.print(feat.name);
21509                            if (feat.version > 0) {
21510                                pw.print(" version=");
21511                                pw.print(feat.version);
21512                            }
21513                            pw.println();
21514                        }
21515                    }
21516                }
21517            }
21518
21519            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21520                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21521                        : "Activity Resolver Table:", "  ", packageName,
21522                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21523                    dumpState.setTitlePrinted(true);
21524                }
21525            }
21526            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21527                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21528                        : "Receiver Resolver Table:", "  ", packageName,
21529                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21530                    dumpState.setTitlePrinted(true);
21531                }
21532            }
21533            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21534                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21535                        : "Service Resolver Table:", "  ", packageName,
21536                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21537                    dumpState.setTitlePrinted(true);
21538                }
21539            }
21540            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21541                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21542                        : "Provider Resolver Table:", "  ", packageName,
21543                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21544                    dumpState.setTitlePrinted(true);
21545                }
21546            }
21547
21548            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21549                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21550                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21551                    int user = mSettings.mPreferredActivities.keyAt(i);
21552                    if (pir.dump(pw,
21553                            dumpState.getTitlePrinted()
21554                                ? "\nPreferred Activities User " + user + ":"
21555                                : "Preferred Activities User " + user + ":", "  ",
21556                            packageName, true, false)) {
21557                        dumpState.setTitlePrinted(true);
21558                    }
21559                }
21560            }
21561
21562            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21563                pw.flush();
21564                FileOutputStream fout = new FileOutputStream(fd);
21565                BufferedOutputStream str = new BufferedOutputStream(fout);
21566                XmlSerializer serializer = new FastXmlSerializer();
21567                try {
21568                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21569                    serializer.startDocument(null, true);
21570                    serializer.setFeature(
21571                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21572                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21573                    serializer.endDocument();
21574                    serializer.flush();
21575                } catch (IllegalArgumentException e) {
21576                    pw.println("Failed writing: " + e);
21577                } catch (IllegalStateException e) {
21578                    pw.println("Failed writing: " + e);
21579                } catch (IOException e) {
21580                    pw.println("Failed writing: " + e);
21581                }
21582            }
21583
21584            if (!checkin
21585                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21586                    && packageName == null) {
21587                pw.println();
21588                int count = mSettings.mPackages.size();
21589                if (count == 0) {
21590                    pw.println("No applications!");
21591                    pw.println();
21592                } else {
21593                    final String prefix = "  ";
21594                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21595                    if (allPackageSettings.size() == 0) {
21596                        pw.println("No domain preferred apps!");
21597                        pw.println();
21598                    } else {
21599                        pw.println("App verification status:");
21600                        pw.println();
21601                        count = 0;
21602                        for (PackageSetting ps : allPackageSettings) {
21603                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21604                            if (ivi == null || ivi.getPackageName() == null) continue;
21605                            pw.println(prefix + "Package: " + ivi.getPackageName());
21606                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21607                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21608                            pw.println();
21609                            count++;
21610                        }
21611                        if (count == 0) {
21612                            pw.println(prefix + "No app verification established.");
21613                            pw.println();
21614                        }
21615                        for (int userId : sUserManager.getUserIds()) {
21616                            pw.println("App linkages for user " + userId + ":");
21617                            pw.println();
21618                            count = 0;
21619                            for (PackageSetting ps : allPackageSettings) {
21620                                final long status = ps.getDomainVerificationStatusForUser(userId);
21621                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21622                                        && !DEBUG_DOMAIN_VERIFICATION) {
21623                                    continue;
21624                                }
21625                                pw.println(prefix + "Package: " + ps.name);
21626                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21627                                String statusStr = IntentFilterVerificationInfo.
21628                                        getStatusStringFromValue(status);
21629                                pw.println(prefix + "Status:  " + statusStr);
21630                                pw.println();
21631                                count++;
21632                            }
21633                            if (count == 0) {
21634                                pw.println(prefix + "No configured app linkages.");
21635                                pw.println();
21636                            }
21637                        }
21638                    }
21639                }
21640            }
21641
21642            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21643                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21644            }
21645
21646            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21647                boolean printedSomething = false;
21648                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21649                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21650                        continue;
21651                    }
21652                    if (!printedSomething) {
21653                        if (dumpState.onTitlePrinted())
21654                            pw.println();
21655                        pw.println("Registered ContentProviders:");
21656                        printedSomething = true;
21657                    }
21658                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21659                    pw.print("    "); pw.println(p.toString());
21660                }
21661                printedSomething = false;
21662                for (Map.Entry<String, PackageParser.Provider> entry :
21663                        mProvidersByAuthority.entrySet()) {
21664                    PackageParser.Provider p = entry.getValue();
21665                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21666                        continue;
21667                    }
21668                    if (!printedSomething) {
21669                        if (dumpState.onTitlePrinted())
21670                            pw.println();
21671                        pw.println("ContentProvider Authorities:");
21672                        printedSomething = true;
21673                    }
21674                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21675                    pw.print("    "); pw.println(p.toString());
21676                    if (p.info != null && p.info.applicationInfo != null) {
21677                        final String appInfo = p.info.applicationInfo.toString();
21678                        pw.print("      applicationInfo="); pw.println(appInfo);
21679                    }
21680                }
21681            }
21682
21683            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21684                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21685            }
21686
21687            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21688                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21689            }
21690
21691            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21692                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21693            }
21694
21695            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21696                if (dumpState.onTitlePrinted()) pw.println();
21697                pw.println("Package Changes:");
21698                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21699                final int K = mChangedPackages.size();
21700                for (int i = 0; i < K; i++) {
21701                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21702                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21703                    final int N = changes.size();
21704                    if (N == 0) {
21705                        pw.print("    "); pw.println("No packages changed");
21706                    } else {
21707                        for (int j = 0; j < N; j++) {
21708                            final String pkgName = changes.valueAt(j);
21709                            final int sequenceNumber = changes.keyAt(j);
21710                            pw.print("    ");
21711                            pw.print("seq=");
21712                            pw.print(sequenceNumber);
21713                            pw.print(", package=");
21714                            pw.println(pkgName);
21715                        }
21716                    }
21717                }
21718            }
21719
21720            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21721                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21722            }
21723
21724            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21725                // XXX should handle packageName != null by dumping only install data that
21726                // the given package is involved with.
21727                if (dumpState.onTitlePrinted()) pw.println();
21728
21729                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21730                ipw.println();
21731                ipw.println("Frozen packages:");
21732                ipw.increaseIndent();
21733                if (mFrozenPackages.size() == 0) {
21734                    ipw.println("(none)");
21735                } else {
21736                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21737                        ipw.println(mFrozenPackages.valueAt(i));
21738                    }
21739                }
21740                ipw.decreaseIndent();
21741            }
21742
21743            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21744                if (dumpState.onTitlePrinted()) pw.println();
21745
21746                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21747                ipw.println();
21748                ipw.println("Loaded volumes:");
21749                ipw.increaseIndent();
21750                if (mLoadedVolumes.size() == 0) {
21751                    ipw.println("(none)");
21752                } else {
21753                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
21754                        ipw.println(mLoadedVolumes.valueAt(i));
21755                    }
21756                }
21757                ipw.decreaseIndent();
21758            }
21759
21760            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21761                    && packageName == null) {
21762                if (dumpState.onTitlePrinted()) pw.println();
21763                pw.println("Service permissions:");
21764
21765                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21766                while (filterIterator.hasNext()) {
21767                    final ServiceIntentInfo info = filterIterator.next();
21768                    final ServiceInfo serviceInfo = info.service.info;
21769                    final String permission = serviceInfo.permission;
21770                    if (permission != null) {
21771                        pw.print("    ");
21772                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21773                        pw.print(": ");
21774                        pw.println(permission);
21775                    }
21776                }
21777            }
21778
21779            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21780                if (dumpState.onTitlePrinted()) pw.println();
21781                dumpDexoptStateLPr(pw, packageName);
21782            }
21783
21784            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21785                if (dumpState.onTitlePrinted()) pw.println();
21786                dumpCompilerStatsLPr(pw, packageName);
21787            }
21788
21789            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21790                if (dumpState.onTitlePrinted()) pw.println();
21791                mSettings.dumpReadMessagesLPr(pw, dumpState);
21792
21793                pw.println();
21794                pw.println("Package warning messages:");
21795                dumpCriticalInfo(pw, null);
21796            }
21797
21798            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21799                dumpCriticalInfo(pw, "msg,");
21800            }
21801        }
21802
21803        // PackageInstaller should be called outside of mPackages lock
21804        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21805            // XXX should handle packageName != null by dumping only install data that
21806            // the given package is involved with.
21807            if (dumpState.onTitlePrinted()) pw.println();
21808            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21809        }
21810    }
21811
21812    private void dumpProto(FileDescriptor fd) {
21813        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21814
21815        synchronized (mPackages) {
21816            final long requiredVerifierPackageToken =
21817                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21818            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21819            proto.write(
21820                    PackageServiceDumpProto.PackageShortProto.UID,
21821                    getPackageUid(
21822                            mRequiredVerifierPackage,
21823                            MATCH_DEBUG_TRIAGED_MISSING,
21824                            UserHandle.USER_SYSTEM));
21825            proto.end(requiredVerifierPackageToken);
21826
21827            if (mIntentFilterVerifierComponent != null) {
21828                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21829                final long verifierPackageToken =
21830                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21831                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21832                proto.write(
21833                        PackageServiceDumpProto.PackageShortProto.UID,
21834                        getPackageUid(
21835                                verifierPackageName,
21836                                MATCH_DEBUG_TRIAGED_MISSING,
21837                                UserHandle.USER_SYSTEM));
21838                proto.end(verifierPackageToken);
21839            }
21840
21841            dumpSharedLibrariesProto(proto);
21842            dumpFeaturesProto(proto);
21843            mSettings.dumpPackagesProto(proto);
21844            mSettings.dumpSharedUsersProto(proto);
21845            dumpCriticalInfo(proto);
21846        }
21847        proto.flush();
21848    }
21849
21850    private void dumpFeaturesProto(ProtoOutputStream proto) {
21851        synchronized (mAvailableFeatures) {
21852            final int count = mAvailableFeatures.size();
21853            for (int i = 0; i < count; i++) {
21854                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21855            }
21856        }
21857    }
21858
21859    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21860        final int count = mSharedLibraries.size();
21861        for (int i = 0; i < count; i++) {
21862            final String libName = mSharedLibraries.keyAt(i);
21863            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21864            if (versionedLib == null) {
21865                continue;
21866            }
21867            final int versionCount = versionedLib.size();
21868            for (int j = 0; j < versionCount; j++) {
21869                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21870                final long sharedLibraryToken =
21871                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21872                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21873                final boolean isJar = (libEntry.path != null);
21874                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21875                if (isJar) {
21876                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21877                } else {
21878                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21879                }
21880                proto.end(sharedLibraryToken);
21881            }
21882        }
21883    }
21884
21885    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21886        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21887        ipw.println();
21888        ipw.println("Dexopt state:");
21889        ipw.increaseIndent();
21890        Collection<PackageParser.Package> packages = null;
21891        if (packageName != null) {
21892            PackageParser.Package targetPackage = mPackages.get(packageName);
21893            if (targetPackage != null) {
21894                packages = Collections.singletonList(targetPackage);
21895            } else {
21896                ipw.println("Unable to find package: " + packageName);
21897                return;
21898            }
21899        } else {
21900            packages = mPackages.values();
21901        }
21902
21903        for (PackageParser.Package pkg : packages) {
21904            ipw.println("[" + pkg.packageName + "]");
21905            ipw.increaseIndent();
21906            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21907                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21908            ipw.decreaseIndent();
21909        }
21910    }
21911
21912    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21913        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21914        ipw.println();
21915        ipw.println("Compiler stats:");
21916        ipw.increaseIndent();
21917        Collection<PackageParser.Package> packages = null;
21918        if (packageName != null) {
21919            PackageParser.Package targetPackage = mPackages.get(packageName);
21920            if (targetPackage != null) {
21921                packages = Collections.singletonList(targetPackage);
21922            } else {
21923                ipw.println("Unable to find package: " + packageName);
21924                return;
21925            }
21926        } else {
21927            packages = mPackages.values();
21928        }
21929
21930        for (PackageParser.Package pkg : packages) {
21931            ipw.println("[" + pkg.packageName + "]");
21932            ipw.increaseIndent();
21933
21934            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21935            if (stats == null) {
21936                ipw.println("(No recorded stats)");
21937            } else {
21938                stats.dump(ipw);
21939            }
21940            ipw.decreaseIndent();
21941        }
21942    }
21943
21944    private String dumpDomainString(String packageName) {
21945        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21946                .getList();
21947        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21948
21949        ArraySet<String> result = new ArraySet<>();
21950        if (iviList.size() > 0) {
21951            for (IntentFilterVerificationInfo ivi : iviList) {
21952                for (String host : ivi.getDomains()) {
21953                    result.add(host);
21954                }
21955            }
21956        }
21957        if (filters != null && filters.size() > 0) {
21958            for (IntentFilter filter : filters) {
21959                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21960                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21961                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21962                    result.addAll(filter.getHostsList());
21963                }
21964            }
21965        }
21966
21967        StringBuilder sb = new StringBuilder(result.size() * 16);
21968        for (String domain : result) {
21969            if (sb.length() > 0) sb.append(" ");
21970            sb.append(domain);
21971        }
21972        return sb.toString();
21973    }
21974
21975    // ------- apps on sdcard specific code -------
21976    static final boolean DEBUG_SD_INSTALL = false;
21977
21978    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21979
21980    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21981
21982    private boolean mMediaMounted = false;
21983
21984    static String getEncryptKey() {
21985        try {
21986            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21987                    SD_ENCRYPTION_KEYSTORE_NAME);
21988            if (sdEncKey == null) {
21989                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21990                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21991                if (sdEncKey == null) {
21992                    Slog.e(TAG, "Failed to create encryption keys");
21993                    return null;
21994                }
21995            }
21996            return sdEncKey;
21997        } catch (NoSuchAlgorithmException nsae) {
21998            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21999            return null;
22000        } catch (IOException ioe) {
22001            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22002            return null;
22003        }
22004    }
22005
22006    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22007            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22008        final int size = infos.size();
22009        final String[] packageNames = new String[size];
22010        final int[] packageUids = new int[size];
22011        for (int i = 0; i < size; i++) {
22012            final ApplicationInfo info = infos.get(i);
22013            packageNames[i] = info.packageName;
22014            packageUids[i] = info.uid;
22015        }
22016        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22017                finishedReceiver);
22018    }
22019
22020    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22021            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22022        sendResourcesChangedBroadcast(mediaStatus, replacing,
22023                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22024    }
22025
22026    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22027            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22028        int size = pkgList.length;
22029        if (size > 0) {
22030            // Send broadcasts here
22031            Bundle extras = new Bundle();
22032            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22033            if (uidArr != null) {
22034                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22035            }
22036            if (replacing) {
22037                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22038            }
22039            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22040                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22041            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
22042        }
22043    }
22044
22045    private void loadPrivatePackages(final VolumeInfo vol) {
22046        mHandler.post(new Runnable() {
22047            @Override
22048            public void run() {
22049                loadPrivatePackagesInner(vol);
22050            }
22051        });
22052    }
22053
22054    private void loadPrivatePackagesInner(VolumeInfo vol) {
22055        final String volumeUuid = vol.fsUuid;
22056        if (TextUtils.isEmpty(volumeUuid)) {
22057            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22058            return;
22059        }
22060
22061        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22062        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22063        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22064
22065        final VersionInfo ver;
22066        final List<PackageSetting> packages;
22067        synchronized (mPackages) {
22068            ver = mSettings.findOrCreateVersion(volumeUuid);
22069            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22070        }
22071
22072        for (PackageSetting ps : packages) {
22073            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22074            synchronized (mInstallLock) {
22075                final PackageParser.Package pkg;
22076                try {
22077                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22078                    loaded.add(pkg.applicationInfo);
22079
22080                } catch (PackageManagerException e) {
22081                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22082                }
22083
22084                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22085                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22086                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22087                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22088                }
22089            }
22090        }
22091
22092        // Reconcile app data for all started/unlocked users
22093        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22094        final UserManager um = mContext.getSystemService(UserManager.class);
22095        UserManagerInternal umInternal = getUserManagerInternal();
22096        for (UserInfo user : um.getUsers()) {
22097            final int flags;
22098            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22099                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22100            } else if (umInternal.isUserRunning(user.id)) {
22101                flags = StorageManager.FLAG_STORAGE_DE;
22102            } else {
22103                continue;
22104            }
22105
22106            try {
22107                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22108                synchronized (mInstallLock) {
22109                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22110                }
22111            } catch (IllegalStateException e) {
22112                // Device was probably ejected, and we'll process that event momentarily
22113                Slog.w(TAG, "Failed to prepare storage: " + e);
22114            }
22115        }
22116
22117        synchronized (mPackages) {
22118            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
22119            if (sdkUpdated) {
22120                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22121                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22122            }
22123            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
22124                    mPermissionCallback);
22125
22126            // Yay, everything is now upgraded
22127            ver.forceCurrent();
22128
22129            mSettings.writeLPr();
22130        }
22131
22132        for (PackageFreezer freezer : freezers) {
22133            freezer.close();
22134        }
22135
22136        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22137        sendResourcesChangedBroadcast(true, false, loaded, null);
22138        mLoadedVolumes.add(vol.getId());
22139    }
22140
22141    private void unloadPrivatePackages(final VolumeInfo vol) {
22142        mHandler.post(new Runnable() {
22143            @Override
22144            public void run() {
22145                unloadPrivatePackagesInner(vol);
22146            }
22147        });
22148    }
22149
22150    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22151        final String volumeUuid = vol.fsUuid;
22152        if (TextUtils.isEmpty(volumeUuid)) {
22153            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22154            return;
22155        }
22156
22157        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22158        synchronized (mInstallLock) {
22159        synchronized (mPackages) {
22160            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22161            for (PackageSetting ps : packages) {
22162                if (ps.pkg == null) continue;
22163
22164                final ApplicationInfo info = ps.pkg.applicationInfo;
22165                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22166                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22167
22168                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22169                        "unloadPrivatePackagesInner")) {
22170                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22171                            false, null)) {
22172                        unloaded.add(info);
22173                    } else {
22174                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22175                    }
22176                }
22177
22178                // Try very hard to release any references to this package
22179                // so we don't risk the system server being killed due to
22180                // open FDs
22181                AttributeCache.instance().removePackage(ps.name);
22182            }
22183
22184            mSettings.writeLPr();
22185        }
22186        }
22187
22188        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22189        sendResourcesChangedBroadcast(false, false, unloaded, null);
22190        mLoadedVolumes.remove(vol.getId());
22191
22192        // Try very hard to release any references to this path so we don't risk
22193        // the system server being killed due to open FDs
22194        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
22195
22196        for (int i = 0; i < 3; i++) {
22197            System.gc();
22198            System.runFinalization();
22199        }
22200    }
22201
22202    private void assertPackageKnown(String volumeUuid, String packageName)
22203            throws PackageManagerException {
22204        synchronized (mPackages) {
22205            // Normalize package name to handle renamed packages
22206            packageName = normalizePackageNameLPr(packageName);
22207
22208            final PackageSetting ps = mSettings.mPackages.get(packageName);
22209            if (ps == null) {
22210                throw new PackageManagerException("Package " + packageName + " is unknown");
22211            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22212                throw new PackageManagerException(
22213                        "Package " + packageName + " found on unknown volume " + volumeUuid
22214                                + "; expected volume " + ps.volumeUuid);
22215            }
22216        }
22217    }
22218
22219    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22220            throws PackageManagerException {
22221        synchronized (mPackages) {
22222            // Normalize package name to handle renamed packages
22223            packageName = normalizePackageNameLPr(packageName);
22224
22225            final PackageSetting ps = mSettings.mPackages.get(packageName);
22226            if (ps == null) {
22227                throw new PackageManagerException("Package " + packageName + " is unknown");
22228            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22229                throw new PackageManagerException(
22230                        "Package " + packageName + " found on unknown volume " + volumeUuid
22231                                + "; expected volume " + ps.volumeUuid);
22232            } else if (!ps.getInstalled(userId)) {
22233                throw new PackageManagerException(
22234                        "Package " + packageName + " not installed for user " + userId);
22235            }
22236        }
22237    }
22238
22239    private List<String> collectAbsoluteCodePaths() {
22240        synchronized (mPackages) {
22241            List<String> codePaths = new ArrayList<>();
22242            final int packageCount = mSettings.mPackages.size();
22243            for (int i = 0; i < packageCount; i++) {
22244                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22245                codePaths.add(ps.codePath.getAbsolutePath());
22246            }
22247            return codePaths;
22248        }
22249    }
22250
22251    /**
22252     * Examine all apps present on given mounted volume, and destroy apps that
22253     * aren't expected, either due to uninstallation or reinstallation on
22254     * another volume.
22255     */
22256    private void reconcileApps(String volumeUuid) {
22257        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22258        List<File> filesToDelete = null;
22259
22260        final File[] files = FileUtils.listFilesOrEmpty(
22261                Environment.getDataAppDirectory(volumeUuid));
22262        for (File file : files) {
22263            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22264                    && !PackageInstallerService.isStageName(file.getName());
22265            if (!isPackage) {
22266                // Ignore entries which are not packages
22267                continue;
22268            }
22269
22270            String absolutePath = file.getAbsolutePath();
22271
22272            boolean pathValid = false;
22273            final int absoluteCodePathCount = absoluteCodePaths.size();
22274            for (int i = 0; i < absoluteCodePathCount; i++) {
22275                String absoluteCodePath = absoluteCodePaths.get(i);
22276                if (absolutePath.startsWith(absoluteCodePath)) {
22277                    pathValid = true;
22278                    break;
22279                }
22280            }
22281
22282            if (!pathValid) {
22283                if (filesToDelete == null) {
22284                    filesToDelete = new ArrayList<>();
22285                }
22286                filesToDelete.add(file);
22287            }
22288        }
22289
22290        if (filesToDelete != null) {
22291            final int fileToDeleteCount = filesToDelete.size();
22292            for (int i = 0; i < fileToDeleteCount; i++) {
22293                File fileToDelete = filesToDelete.get(i);
22294                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22295                synchronized (mInstallLock) {
22296                    removeCodePathLI(fileToDelete);
22297                }
22298            }
22299        }
22300    }
22301
22302    /**
22303     * Reconcile all app data for the given user.
22304     * <p>
22305     * Verifies that directories exist and that ownership and labeling is
22306     * correct for all installed apps on all mounted volumes.
22307     */
22308    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22309        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22310        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22311            final String volumeUuid = vol.getFsUuid();
22312            synchronized (mInstallLock) {
22313                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22314            }
22315        }
22316    }
22317
22318    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22319            boolean migrateAppData) {
22320        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22321    }
22322
22323    /**
22324     * Reconcile all app data on given mounted volume.
22325     * <p>
22326     * Destroys app data that isn't expected, either due to uninstallation or
22327     * reinstallation on another volume.
22328     * <p>
22329     * Verifies that directories exist and that ownership and labeling is
22330     * correct for all installed apps.
22331     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22332     */
22333    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22334            boolean migrateAppData, boolean onlyCoreApps) {
22335        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22336                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22337        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22338
22339        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22340        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22341
22342        // First look for stale data that doesn't belong, and check if things
22343        // have changed since we did our last restorecon
22344        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22345            if (StorageManager.isFileEncryptedNativeOrEmulated()
22346                    && !StorageManager.isUserKeyUnlocked(userId)) {
22347                throw new RuntimeException(
22348                        "Yikes, someone asked us to reconcile CE storage while " + userId
22349                                + " was still locked; this would have caused massive data loss!");
22350            }
22351
22352            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22353            for (File file : files) {
22354                final String packageName = file.getName();
22355                try {
22356                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22357                } catch (PackageManagerException e) {
22358                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22359                    try {
22360                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22361                                StorageManager.FLAG_STORAGE_CE, 0);
22362                    } catch (InstallerException e2) {
22363                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22364                    }
22365                }
22366            }
22367        }
22368        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22369            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22370            for (File file : files) {
22371                final String packageName = file.getName();
22372                try {
22373                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22374                } catch (PackageManagerException e) {
22375                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22376                    try {
22377                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22378                                StorageManager.FLAG_STORAGE_DE, 0);
22379                    } catch (InstallerException e2) {
22380                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22381                    }
22382                }
22383            }
22384        }
22385
22386        // Ensure that data directories are ready to roll for all packages
22387        // installed for this volume and user
22388        final List<PackageSetting> packages;
22389        synchronized (mPackages) {
22390            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22391        }
22392        int preparedCount = 0;
22393        for (PackageSetting ps : packages) {
22394            final String packageName = ps.name;
22395            if (ps.pkg == null) {
22396                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22397                // TODO: might be due to legacy ASEC apps; we should circle back
22398                // and reconcile again once they're scanned
22399                continue;
22400            }
22401            // Skip non-core apps if requested
22402            if (onlyCoreApps && !ps.pkg.coreApp) {
22403                result.add(packageName);
22404                continue;
22405            }
22406
22407            if (ps.getInstalled(userId)) {
22408                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22409                preparedCount++;
22410            }
22411        }
22412
22413        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22414        return result;
22415    }
22416
22417    /**
22418     * Prepare app data for the given app just after it was installed or
22419     * upgraded. This method carefully only touches users that it's installed
22420     * for, and it forces a restorecon to handle any seinfo changes.
22421     * <p>
22422     * Verifies that directories exist and that ownership and labeling is
22423     * correct for all installed apps. If there is an ownership mismatch, it
22424     * will try recovering system apps by wiping data; third-party app data is
22425     * left intact.
22426     * <p>
22427     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22428     */
22429    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22430        final PackageSetting ps;
22431        synchronized (mPackages) {
22432            ps = mSettings.mPackages.get(pkg.packageName);
22433            mSettings.writeKernelMappingLPr(ps);
22434        }
22435
22436        final UserManager um = mContext.getSystemService(UserManager.class);
22437        UserManagerInternal umInternal = getUserManagerInternal();
22438        for (UserInfo user : um.getUsers()) {
22439            final int flags;
22440            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22441                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22442            } else if (umInternal.isUserRunning(user.id)) {
22443                flags = StorageManager.FLAG_STORAGE_DE;
22444            } else {
22445                continue;
22446            }
22447
22448            if (ps.getInstalled(user.id)) {
22449                // TODO: when user data is locked, mark that we're still dirty
22450                prepareAppDataLIF(pkg, user.id, flags);
22451            }
22452        }
22453    }
22454
22455    /**
22456     * Prepare app data for the given app.
22457     * <p>
22458     * Verifies that directories exist and that ownership and labeling is
22459     * correct for all installed apps. If there is an ownership mismatch, this
22460     * will try recovering system apps by wiping data; third-party app data is
22461     * left intact.
22462     */
22463    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22464        if (pkg == null) {
22465            Slog.wtf(TAG, "Package was null!", new Throwable());
22466            return;
22467        }
22468        prepareAppDataLeafLIF(pkg, userId, flags);
22469        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22470        for (int i = 0; i < childCount; i++) {
22471            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22472        }
22473    }
22474
22475    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22476            boolean maybeMigrateAppData) {
22477        prepareAppDataLIF(pkg, userId, flags);
22478
22479        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22480            // We may have just shuffled around app data directories, so
22481            // prepare them one more time
22482            prepareAppDataLIF(pkg, userId, flags);
22483        }
22484    }
22485
22486    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22487        if (DEBUG_APP_DATA) {
22488            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22489                    + Integer.toHexString(flags));
22490        }
22491
22492        final PackageSetting ps;
22493        synchronized (mPackages) {
22494            ps = mSettings.mPackages.get(pkg.packageName);
22495        }
22496        final String volumeUuid = pkg.volumeUuid;
22497        final String packageName = pkg.packageName;
22498
22499        ApplicationInfo app = (ps == null)
22500                ? pkg.applicationInfo
22501                : PackageParser.generateApplicationInfo(pkg, 0, ps.readUserState(userId), userId);
22502        if (app == null) {
22503            app = pkg.applicationInfo;
22504        }
22505
22506        final int appId = UserHandle.getAppId(app.uid);
22507
22508        Preconditions.checkNotNull(app.seInfo);
22509
22510        final String seInfo = app.seInfo + (app.seInfoUser != null ? app.seInfoUser : "");
22511        long ceDataInode = -1;
22512        try {
22513            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22514                    appId, seInfo, app.targetSdkVersion);
22515        } catch (InstallerException e) {
22516            if (app.isSystemApp()) {
22517                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22518                        + ", but trying to recover: " + e);
22519                destroyAppDataLeafLIF(pkg, userId, flags);
22520                try {
22521                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22522                            appId, seInfo, app.targetSdkVersion);
22523                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22524                } catch (InstallerException e2) {
22525                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22526                }
22527            } else {
22528                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22529            }
22530        }
22531        // Prepare the application profiles only for upgrades and first boot (so that we don't
22532        // repeat the same operation at each boot).
22533        // We only have to cover the upgrade and first boot here because for app installs we
22534        // prepare the profiles before invoking dexopt (in installPackageLI).
22535        //
22536        // We also have to cover non system users because we do not call the usual install package
22537        // methods for them.
22538        if (mIsUpgrade || mFirstBoot || (userId != UserHandle.USER_SYSTEM)) {
22539            mArtManagerService.prepareAppProfiles(pkg, userId);
22540        }
22541
22542        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22543            // TODO: mark this structure as dirty so we persist it!
22544            synchronized (mPackages) {
22545                if (ps != null) {
22546                    ps.setCeDataInode(ceDataInode, userId);
22547                }
22548            }
22549        }
22550
22551        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22552    }
22553
22554    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22555        if (pkg == null) {
22556            Slog.wtf(TAG, "Package was null!", new Throwable());
22557            return;
22558        }
22559        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22560        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22561        for (int i = 0; i < childCount; i++) {
22562            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22563        }
22564    }
22565
22566    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22567        final String volumeUuid = pkg.volumeUuid;
22568        final String packageName = pkg.packageName;
22569        final ApplicationInfo app = pkg.applicationInfo;
22570
22571        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22572            // Create a native library symlink only if we have native libraries
22573            // and if the native libraries are 32 bit libraries. We do not provide
22574            // this symlink for 64 bit libraries.
22575            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22576                final String nativeLibPath = app.nativeLibraryDir;
22577                try {
22578                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22579                            nativeLibPath, userId);
22580                } catch (InstallerException e) {
22581                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22582                }
22583            }
22584        }
22585    }
22586
22587    /**
22588     * For system apps on non-FBE devices, this method migrates any existing
22589     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22590     * requested by the app.
22591     */
22592    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22593        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
22594                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22595            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22596                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22597            try {
22598                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22599                        storageTarget);
22600            } catch (InstallerException e) {
22601                logCriticalInfo(Log.WARN,
22602                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22603            }
22604            return true;
22605        } else {
22606            return false;
22607        }
22608    }
22609
22610    public PackageFreezer freezePackage(String packageName, String killReason) {
22611        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22612    }
22613
22614    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22615        return new PackageFreezer(packageName, userId, killReason);
22616    }
22617
22618    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22619            String killReason) {
22620        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22621    }
22622
22623    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22624            String killReason) {
22625        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22626            return new PackageFreezer();
22627        } else {
22628            return freezePackage(packageName, userId, killReason);
22629        }
22630    }
22631
22632    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22633            String killReason) {
22634        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22635    }
22636
22637    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22638            String killReason) {
22639        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22640            return new PackageFreezer();
22641        } else {
22642            return freezePackage(packageName, userId, killReason);
22643        }
22644    }
22645
22646    /**
22647     * Class that freezes and kills the given package upon creation, and
22648     * unfreezes it upon closing. This is typically used when doing surgery on
22649     * app code/data to prevent the app from running while you're working.
22650     */
22651    private class PackageFreezer implements AutoCloseable {
22652        private final String mPackageName;
22653        private final PackageFreezer[] mChildren;
22654
22655        private final boolean mWeFroze;
22656
22657        private final AtomicBoolean mClosed = new AtomicBoolean();
22658        private final CloseGuard mCloseGuard = CloseGuard.get();
22659
22660        /**
22661         * Create and return a stub freezer that doesn't actually do anything,
22662         * typically used when someone requested
22663         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22664         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22665         */
22666        public PackageFreezer() {
22667            mPackageName = null;
22668            mChildren = null;
22669            mWeFroze = false;
22670            mCloseGuard.open("close");
22671        }
22672
22673        public PackageFreezer(String packageName, int userId, String killReason) {
22674            synchronized (mPackages) {
22675                mPackageName = packageName;
22676                mWeFroze = mFrozenPackages.add(mPackageName);
22677
22678                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22679                if (ps != null) {
22680                    killApplication(ps.name, ps.appId, userId, killReason);
22681                }
22682
22683                final PackageParser.Package p = mPackages.get(packageName);
22684                if (p != null && p.childPackages != null) {
22685                    final int N = p.childPackages.size();
22686                    mChildren = new PackageFreezer[N];
22687                    for (int i = 0; i < N; i++) {
22688                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22689                                userId, killReason);
22690                    }
22691                } else {
22692                    mChildren = null;
22693                }
22694            }
22695            mCloseGuard.open("close");
22696        }
22697
22698        @Override
22699        protected void finalize() throws Throwable {
22700            try {
22701                if (mCloseGuard != null) {
22702                    mCloseGuard.warnIfOpen();
22703                }
22704
22705                close();
22706            } finally {
22707                super.finalize();
22708            }
22709        }
22710
22711        @Override
22712        public void close() {
22713            mCloseGuard.close();
22714            if (mClosed.compareAndSet(false, true)) {
22715                synchronized (mPackages) {
22716                    if (mWeFroze) {
22717                        mFrozenPackages.remove(mPackageName);
22718                    }
22719
22720                    if (mChildren != null) {
22721                        for (PackageFreezer freezer : mChildren) {
22722                            freezer.close();
22723                        }
22724                    }
22725                }
22726            }
22727        }
22728    }
22729
22730    /**
22731     * Verify that given package is currently frozen.
22732     */
22733    private void checkPackageFrozen(String packageName) {
22734        synchronized (mPackages) {
22735            if (!mFrozenPackages.contains(packageName)) {
22736                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22737            }
22738        }
22739    }
22740
22741    @Override
22742    public int movePackage(final String packageName, final String volumeUuid) {
22743        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22744
22745        final int callingUid = Binder.getCallingUid();
22746        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22747        final int moveId = mNextMoveId.getAndIncrement();
22748        mHandler.post(new Runnable() {
22749            @Override
22750            public void run() {
22751                try {
22752                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22753                } catch (PackageManagerException e) {
22754                    Slog.w(TAG, "Failed to move " + packageName, e);
22755                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22756                }
22757            }
22758        });
22759        return moveId;
22760    }
22761
22762    private void movePackageInternal(final String packageName, final String volumeUuid,
22763            final int moveId, final int callingUid, UserHandle user)
22764                    throws PackageManagerException {
22765        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22766        final PackageManager pm = mContext.getPackageManager();
22767
22768        final boolean currentAsec;
22769        final String currentVolumeUuid;
22770        final File codeFile;
22771        final String installerPackageName;
22772        final String packageAbiOverride;
22773        final int appId;
22774        final String seinfo;
22775        final String label;
22776        final int targetSdkVersion;
22777        final PackageFreezer freezer;
22778        final int[] installedUserIds;
22779
22780        // reader
22781        synchronized (mPackages) {
22782            final PackageParser.Package pkg = mPackages.get(packageName);
22783            final PackageSetting ps = mSettings.mPackages.get(packageName);
22784            if (pkg == null
22785                    || ps == null
22786                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22787                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22788            }
22789            if (pkg.applicationInfo.isSystemApp()) {
22790                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22791                        "Cannot move system application");
22792            }
22793
22794            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22795            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22796                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22797            if (isInternalStorage && !allow3rdPartyOnInternal) {
22798                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22799                        "3rd party apps are not allowed on internal storage");
22800            }
22801
22802            if (pkg.applicationInfo.isExternalAsec()) {
22803                currentAsec = true;
22804                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22805            } else if (pkg.applicationInfo.isForwardLocked()) {
22806                currentAsec = true;
22807                currentVolumeUuid = "forward_locked";
22808            } else {
22809                currentAsec = false;
22810                currentVolumeUuid = ps.volumeUuid;
22811
22812                final File probe = new File(pkg.codePath);
22813                final File probeOat = new File(probe, "oat");
22814                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22815                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22816                            "Move only supported for modern cluster style installs");
22817                }
22818            }
22819
22820            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22821                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22822                        "Package already moved to " + volumeUuid);
22823            }
22824            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22825                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22826                        "Device admin cannot be moved");
22827            }
22828
22829            if (mFrozenPackages.contains(packageName)) {
22830                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22831                        "Failed to move already frozen package");
22832            }
22833
22834            codeFile = new File(pkg.codePath);
22835            installerPackageName = ps.installerPackageName;
22836            packageAbiOverride = ps.cpuAbiOverrideString;
22837            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22838            seinfo = pkg.applicationInfo.seInfo;
22839            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22840            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22841            freezer = freezePackage(packageName, "movePackageInternal");
22842            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22843        }
22844
22845        final Bundle extras = new Bundle();
22846        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22847        extras.putString(Intent.EXTRA_TITLE, label);
22848        mMoveCallbacks.notifyCreated(moveId, extras);
22849
22850        int installFlags;
22851        final boolean moveCompleteApp;
22852        final File measurePath;
22853
22854        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22855            installFlags = INSTALL_INTERNAL;
22856            moveCompleteApp = !currentAsec;
22857            measurePath = Environment.getDataAppDirectory(volumeUuid);
22858        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22859            installFlags = INSTALL_EXTERNAL;
22860            moveCompleteApp = false;
22861            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22862        } else {
22863            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22864            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22865                    || !volume.isMountedWritable()) {
22866                freezer.close();
22867                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22868                        "Move location not mounted private volume");
22869            }
22870
22871            Preconditions.checkState(!currentAsec);
22872
22873            installFlags = INSTALL_INTERNAL;
22874            moveCompleteApp = true;
22875            measurePath = Environment.getDataAppDirectory(volumeUuid);
22876        }
22877
22878        // If we're moving app data around, we need all the users unlocked
22879        if (moveCompleteApp) {
22880            for (int userId : installedUserIds) {
22881                if (StorageManager.isFileEncryptedNativeOrEmulated()
22882                        && !StorageManager.isUserKeyUnlocked(userId)) {
22883                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22884                            "User " + userId + " must be unlocked");
22885                }
22886            }
22887        }
22888
22889        final PackageStats stats = new PackageStats(null, -1);
22890        synchronized (mInstaller) {
22891            for (int userId : installedUserIds) {
22892                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22893                    freezer.close();
22894                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22895                            "Failed to measure package size");
22896                }
22897            }
22898        }
22899
22900        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22901                + stats.dataSize);
22902
22903        final long startFreeBytes = measurePath.getUsableSpace();
22904        final long sizeBytes;
22905        if (moveCompleteApp) {
22906            sizeBytes = stats.codeSize + stats.dataSize;
22907        } else {
22908            sizeBytes = stats.codeSize;
22909        }
22910
22911        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22912            freezer.close();
22913            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22914                    "Not enough free space to move");
22915        }
22916
22917        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22918
22919        final CountDownLatch installedLatch = new CountDownLatch(1);
22920        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22921            @Override
22922            public void onUserActionRequired(Intent intent) throws RemoteException {
22923                throw new IllegalStateException();
22924            }
22925
22926            @Override
22927            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22928                    Bundle extras) throws RemoteException {
22929                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22930                        + PackageManager.installStatusToString(returnCode, msg));
22931
22932                installedLatch.countDown();
22933                freezer.close();
22934
22935                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22936                switch (status) {
22937                    case PackageInstaller.STATUS_SUCCESS:
22938                        mMoveCallbacks.notifyStatusChanged(moveId,
22939                                PackageManager.MOVE_SUCCEEDED);
22940                        break;
22941                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22942                        mMoveCallbacks.notifyStatusChanged(moveId,
22943                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22944                        break;
22945                    default:
22946                        mMoveCallbacks.notifyStatusChanged(moveId,
22947                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22948                        break;
22949                }
22950            }
22951        };
22952
22953        final MoveInfo move;
22954        if (moveCompleteApp) {
22955            // Kick off a thread to report progress estimates
22956            new Thread() {
22957                @Override
22958                public void run() {
22959                    while (true) {
22960                        try {
22961                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22962                                break;
22963                            }
22964                        } catch (InterruptedException ignored) {
22965                        }
22966
22967                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22968                        final int progress = 10 + (int) MathUtils.constrain(
22969                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22970                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22971                    }
22972                }
22973            }.start();
22974
22975            final String dataAppName = codeFile.getName();
22976            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22977                    dataAppName, appId, seinfo, targetSdkVersion);
22978        } else {
22979            move = null;
22980        }
22981
22982        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22983
22984        final Message msg = mHandler.obtainMessage(INIT_COPY);
22985        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22986        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22987                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22988                packageAbiOverride, null /*grantedPermissions*/,
22989                PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
22990        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22991        msg.obj = params;
22992
22993        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22994                System.identityHashCode(msg.obj));
22995        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22996                System.identityHashCode(msg.obj));
22997
22998        mHandler.sendMessage(msg);
22999    }
23000
23001    @Override
23002    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23003        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23004
23005        final int realMoveId = mNextMoveId.getAndIncrement();
23006        final Bundle extras = new Bundle();
23007        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23008        mMoveCallbacks.notifyCreated(realMoveId, extras);
23009
23010        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23011            @Override
23012            public void onCreated(int moveId, Bundle extras) {
23013                // Ignored
23014            }
23015
23016            @Override
23017            public void onStatusChanged(int moveId, int status, long estMillis) {
23018                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23019            }
23020        };
23021
23022        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23023        storage.setPrimaryStorageUuid(volumeUuid, callback);
23024        return realMoveId;
23025    }
23026
23027    @Override
23028    public int getMoveStatus(int moveId) {
23029        mContext.enforceCallingOrSelfPermission(
23030                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23031        return mMoveCallbacks.mLastStatus.get(moveId);
23032    }
23033
23034    @Override
23035    public void registerMoveCallback(IPackageMoveObserver callback) {
23036        mContext.enforceCallingOrSelfPermission(
23037                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23038        mMoveCallbacks.register(callback);
23039    }
23040
23041    @Override
23042    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23043        mContext.enforceCallingOrSelfPermission(
23044                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23045        mMoveCallbacks.unregister(callback);
23046    }
23047
23048    @Override
23049    public boolean setInstallLocation(int loc) {
23050        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23051                null);
23052        if (getInstallLocation() == loc) {
23053            return true;
23054        }
23055        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23056                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23057            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23058                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23059            return true;
23060        }
23061        return false;
23062   }
23063
23064    @Override
23065    public int getInstallLocation() {
23066        // allow instant app access
23067        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23068                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23069                PackageHelper.APP_INSTALL_AUTO);
23070    }
23071
23072    /** Called by UserManagerService */
23073    void cleanUpUser(UserManagerService userManager, int userHandle) {
23074        synchronized (mPackages) {
23075            mDirtyUsers.remove(userHandle);
23076            mUserNeedsBadging.delete(userHandle);
23077            mSettings.removeUserLPw(userHandle);
23078            mPendingBroadcasts.remove(userHandle);
23079            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23080            removeUnusedPackagesLPw(userManager, userHandle);
23081        }
23082    }
23083
23084    /**
23085     * We're removing userHandle and would like to remove any downloaded packages
23086     * that are no longer in use by any other user.
23087     * @param userHandle the user being removed
23088     */
23089    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23090        final boolean DEBUG_CLEAN_APKS = false;
23091        int [] users = userManager.getUserIds();
23092        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23093        while (psit.hasNext()) {
23094            PackageSetting ps = psit.next();
23095            if (ps.pkg == null) {
23096                continue;
23097            }
23098            final String packageName = ps.pkg.packageName;
23099            // Skip over if system app
23100            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23101                continue;
23102            }
23103            if (DEBUG_CLEAN_APKS) {
23104                Slog.i(TAG, "Checking package " + packageName);
23105            }
23106            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23107            if (keep) {
23108                if (DEBUG_CLEAN_APKS) {
23109                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23110                }
23111            } else {
23112                for (int i = 0; i < users.length; i++) {
23113                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23114                        keep = true;
23115                        if (DEBUG_CLEAN_APKS) {
23116                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23117                                    + users[i]);
23118                        }
23119                        break;
23120                    }
23121                }
23122            }
23123            if (!keep) {
23124                if (DEBUG_CLEAN_APKS) {
23125                    Slog.i(TAG, "  Removing package " + packageName);
23126                }
23127                mHandler.post(new Runnable() {
23128                    public void run() {
23129                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23130                                userHandle, 0);
23131                    } //end run
23132                });
23133            }
23134        }
23135    }
23136
23137    /** Called by UserManagerService */
23138    void createNewUser(int userId, String[] disallowedPackages) {
23139        synchronized (mInstallLock) {
23140            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23141        }
23142        synchronized (mPackages) {
23143            scheduleWritePackageRestrictionsLocked(userId);
23144            scheduleWritePackageListLocked(userId);
23145            applyFactoryDefaultBrowserLPw(userId);
23146            primeDomainVerificationsLPw(userId);
23147        }
23148    }
23149
23150    void onNewUserCreated(final int userId) {
23151        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23152        synchronized(mPackages) {
23153            // If permission review for legacy apps is required, we represent
23154            // dagerous permissions for such apps as always granted runtime
23155            // permissions to keep per user flag state whether review is needed.
23156            // Hence, if a new user is added we have to propagate dangerous
23157            // permission grants for these legacy apps.
23158            if (mSettings.mPermissions.mPermissionReviewRequired) {
23159// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
23160                mPermissionManager.updateAllPermissions(
23161                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
23162                        mPermissionCallback);
23163            }
23164        }
23165    }
23166
23167    @Override
23168    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23169        mContext.enforceCallingOrSelfPermission(
23170                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23171                "Only package verification agents can read the verifier device identity");
23172
23173        synchronized (mPackages) {
23174            return mSettings.getVerifierDeviceIdentityLPw();
23175        }
23176    }
23177
23178    @Override
23179    public void setPermissionEnforced(String permission, boolean enforced) {
23180        // TODO: Now that we no longer change GID for storage, this should to away.
23181        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23182                "setPermissionEnforced");
23183        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23184            synchronized (mPackages) {
23185                if (mSettings.mReadExternalStorageEnforced == null
23186                        || mSettings.mReadExternalStorageEnforced != enforced) {
23187                    mSettings.mReadExternalStorageEnforced =
23188                            enforced ? Boolean.TRUE : Boolean.FALSE;
23189                    mSettings.writeLPr();
23190                }
23191            }
23192            // kill any non-foreground processes so we restart them and
23193            // grant/revoke the GID.
23194            final IActivityManager am = ActivityManager.getService();
23195            if (am != null) {
23196                final long token = Binder.clearCallingIdentity();
23197                try {
23198                    am.killProcessesBelowForeground("setPermissionEnforcement");
23199                } catch (RemoteException e) {
23200                } finally {
23201                    Binder.restoreCallingIdentity(token);
23202                }
23203            }
23204        } else {
23205            throw new IllegalArgumentException("No selective enforcement for " + permission);
23206        }
23207    }
23208
23209    @Override
23210    @Deprecated
23211    public boolean isPermissionEnforced(String permission) {
23212        // allow instant applications
23213        return true;
23214    }
23215
23216    @Override
23217    public boolean isStorageLow() {
23218        // allow instant applications
23219        final long token = Binder.clearCallingIdentity();
23220        try {
23221            final DeviceStorageMonitorInternal
23222                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23223            if (dsm != null) {
23224                return dsm.isMemoryLow();
23225            } else {
23226                return false;
23227            }
23228        } finally {
23229            Binder.restoreCallingIdentity(token);
23230        }
23231    }
23232
23233    @Override
23234    public IPackageInstaller getPackageInstaller() {
23235        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23236            return null;
23237        }
23238        return mInstallerService;
23239    }
23240
23241    @Override
23242    public IArtManager getArtManager() {
23243        return mArtManagerService;
23244    }
23245
23246    private boolean userNeedsBadging(int userId) {
23247        int index = mUserNeedsBadging.indexOfKey(userId);
23248        if (index < 0) {
23249            final UserInfo userInfo;
23250            final long token = Binder.clearCallingIdentity();
23251            try {
23252                userInfo = sUserManager.getUserInfo(userId);
23253            } finally {
23254                Binder.restoreCallingIdentity(token);
23255            }
23256            final boolean b;
23257            if (userInfo != null && userInfo.isManagedProfile()) {
23258                b = true;
23259            } else {
23260                b = false;
23261            }
23262            mUserNeedsBadging.put(userId, b);
23263            return b;
23264        }
23265        return mUserNeedsBadging.valueAt(index);
23266    }
23267
23268    @Override
23269    public KeySet getKeySetByAlias(String packageName, String alias) {
23270        if (packageName == null || alias == null) {
23271            return null;
23272        }
23273        synchronized(mPackages) {
23274            final PackageParser.Package pkg = mPackages.get(packageName);
23275            if (pkg == null) {
23276                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23277                throw new IllegalArgumentException("Unknown package: " + packageName);
23278            }
23279            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23280            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
23281                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
23282                throw new IllegalArgumentException("Unknown package: " + packageName);
23283            }
23284            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23285            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23286        }
23287    }
23288
23289    @Override
23290    public KeySet getSigningKeySet(String packageName) {
23291        if (packageName == null) {
23292            return null;
23293        }
23294        synchronized(mPackages) {
23295            final int callingUid = Binder.getCallingUid();
23296            final int callingUserId = UserHandle.getUserId(callingUid);
23297            final PackageParser.Package pkg = mPackages.get(packageName);
23298            if (pkg == null) {
23299                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23300                throw new IllegalArgumentException("Unknown package: " + packageName);
23301            }
23302            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23303            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23304                // filter and pretend the package doesn't exist
23305                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23306                        + ", uid:" + callingUid);
23307                throw new IllegalArgumentException("Unknown package: " + packageName);
23308            }
23309            if (pkg.applicationInfo.uid != callingUid
23310                    && Process.SYSTEM_UID != callingUid) {
23311                throw new SecurityException("May not access signing KeySet of other apps.");
23312            }
23313            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23314            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23315        }
23316    }
23317
23318    @Override
23319    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23320        final int callingUid = Binder.getCallingUid();
23321        if (getInstantAppPackageName(callingUid) != null) {
23322            return false;
23323        }
23324        if (packageName == null || ks == null) {
23325            return false;
23326        }
23327        synchronized(mPackages) {
23328            final PackageParser.Package pkg = mPackages.get(packageName);
23329            if (pkg == null
23330                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23331                            UserHandle.getUserId(callingUid))) {
23332                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23333                throw new IllegalArgumentException("Unknown package: " + packageName);
23334            }
23335            IBinder ksh = ks.getToken();
23336            if (ksh instanceof KeySetHandle) {
23337                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23338                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23339            }
23340            return false;
23341        }
23342    }
23343
23344    @Override
23345    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23346        final int callingUid = Binder.getCallingUid();
23347        if (getInstantAppPackageName(callingUid) != null) {
23348            return false;
23349        }
23350        if (packageName == null || ks == null) {
23351            return false;
23352        }
23353        synchronized(mPackages) {
23354            final PackageParser.Package pkg = mPackages.get(packageName);
23355            if (pkg == null
23356                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23357                            UserHandle.getUserId(callingUid))) {
23358                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23359                throw new IllegalArgumentException("Unknown package: " + packageName);
23360            }
23361            IBinder ksh = ks.getToken();
23362            if (ksh instanceof KeySetHandle) {
23363                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23364                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23365            }
23366            return false;
23367        }
23368    }
23369
23370    private void deletePackageIfUnusedLPr(final String packageName) {
23371        PackageSetting ps = mSettings.mPackages.get(packageName);
23372        if (ps == null) {
23373            return;
23374        }
23375        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23376            // TODO Implement atomic delete if package is unused
23377            // It is currently possible that the package will be deleted even if it is installed
23378            // after this method returns.
23379            mHandler.post(new Runnable() {
23380                public void run() {
23381                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23382                            0, PackageManager.DELETE_ALL_USERS);
23383                }
23384            });
23385        }
23386    }
23387
23388    /**
23389     * Check and throw if the given before/after packages would be considered a
23390     * downgrade.
23391     */
23392    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23393            throws PackageManagerException {
23394        if (after.getLongVersionCode() < before.getLongVersionCode()) {
23395            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23396                    "Update version code " + after.versionCode + " is older than current "
23397                    + before.getLongVersionCode());
23398        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
23399            if (after.baseRevisionCode < before.baseRevisionCode) {
23400                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23401                        "Update base revision code " + after.baseRevisionCode
23402                        + " is older than current " + before.baseRevisionCode);
23403            }
23404
23405            if (!ArrayUtils.isEmpty(after.splitNames)) {
23406                for (int i = 0; i < after.splitNames.length; i++) {
23407                    final String splitName = after.splitNames[i];
23408                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23409                    if (j != -1) {
23410                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23411                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23412                                    "Update split " + splitName + " revision code "
23413                                    + after.splitRevisionCodes[i] + " is older than current "
23414                                    + before.splitRevisionCodes[j]);
23415                        }
23416                    }
23417                }
23418            }
23419        }
23420    }
23421
23422    private static class MoveCallbacks extends Handler {
23423        private static final int MSG_CREATED = 1;
23424        private static final int MSG_STATUS_CHANGED = 2;
23425
23426        private final RemoteCallbackList<IPackageMoveObserver>
23427                mCallbacks = new RemoteCallbackList<>();
23428
23429        private final SparseIntArray mLastStatus = new SparseIntArray();
23430
23431        public MoveCallbacks(Looper looper) {
23432            super(looper);
23433        }
23434
23435        public void register(IPackageMoveObserver callback) {
23436            mCallbacks.register(callback);
23437        }
23438
23439        public void unregister(IPackageMoveObserver callback) {
23440            mCallbacks.unregister(callback);
23441        }
23442
23443        @Override
23444        public void handleMessage(Message msg) {
23445            final SomeArgs args = (SomeArgs) msg.obj;
23446            final int n = mCallbacks.beginBroadcast();
23447            for (int i = 0; i < n; i++) {
23448                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23449                try {
23450                    invokeCallback(callback, msg.what, args);
23451                } catch (RemoteException ignored) {
23452                }
23453            }
23454            mCallbacks.finishBroadcast();
23455            args.recycle();
23456        }
23457
23458        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23459                throws RemoteException {
23460            switch (what) {
23461                case MSG_CREATED: {
23462                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23463                    break;
23464                }
23465                case MSG_STATUS_CHANGED: {
23466                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23467                    break;
23468                }
23469            }
23470        }
23471
23472        private void notifyCreated(int moveId, Bundle extras) {
23473            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23474
23475            final SomeArgs args = SomeArgs.obtain();
23476            args.argi1 = moveId;
23477            args.arg2 = extras;
23478            obtainMessage(MSG_CREATED, args).sendToTarget();
23479        }
23480
23481        private void notifyStatusChanged(int moveId, int status) {
23482            notifyStatusChanged(moveId, status, -1);
23483        }
23484
23485        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23486            Slog.v(TAG, "Move " + moveId + " status " + status);
23487
23488            final SomeArgs args = SomeArgs.obtain();
23489            args.argi1 = moveId;
23490            args.argi2 = status;
23491            args.arg3 = estMillis;
23492            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23493
23494            synchronized (mLastStatus) {
23495                mLastStatus.put(moveId, status);
23496            }
23497        }
23498    }
23499
23500    private final static class OnPermissionChangeListeners extends Handler {
23501        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23502
23503        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23504                new RemoteCallbackList<>();
23505
23506        public OnPermissionChangeListeners(Looper looper) {
23507            super(looper);
23508        }
23509
23510        @Override
23511        public void handleMessage(Message msg) {
23512            switch (msg.what) {
23513                case MSG_ON_PERMISSIONS_CHANGED: {
23514                    final int uid = msg.arg1;
23515                    handleOnPermissionsChanged(uid);
23516                } break;
23517            }
23518        }
23519
23520        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23521            mPermissionListeners.register(listener);
23522
23523        }
23524
23525        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23526            mPermissionListeners.unregister(listener);
23527        }
23528
23529        public void onPermissionsChanged(int uid) {
23530            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23531                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23532            }
23533        }
23534
23535        private void handleOnPermissionsChanged(int uid) {
23536            final int count = mPermissionListeners.beginBroadcast();
23537            try {
23538                for (int i = 0; i < count; i++) {
23539                    IOnPermissionsChangeListener callback = mPermissionListeners
23540                            .getBroadcastItem(i);
23541                    try {
23542                        callback.onPermissionsChanged(uid);
23543                    } catch (RemoteException e) {
23544                        Log.e(TAG, "Permission listener is dead", e);
23545                    }
23546                }
23547            } finally {
23548                mPermissionListeners.finishBroadcast();
23549            }
23550        }
23551    }
23552
23553    private class PackageManagerNative extends IPackageManagerNative.Stub {
23554        @Override
23555        public String[] getNamesForUids(int[] uids) throws RemoteException {
23556            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23557            // massage results so they can be parsed by the native binder
23558            for (int i = results.length - 1; i >= 0; --i) {
23559                if (results[i] == null) {
23560                    results[i] = "";
23561                }
23562            }
23563            return results;
23564        }
23565
23566        // NB: this differentiates between preloads and sideloads
23567        @Override
23568        public String getInstallerForPackage(String packageName) throws RemoteException {
23569            final String installerName = getInstallerPackageName(packageName);
23570            if (!TextUtils.isEmpty(installerName)) {
23571                return installerName;
23572            }
23573            // differentiate between preload and sideload
23574            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23575            ApplicationInfo appInfo = getApplicationInfo(packageName,
23576                                    /*flags*/ 0,
23577                                    /*userId*/ callingUser);
23578            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23579                return "preload";
23580            }
23581            return "";
23582        }
23583
23584        @Override
23585        public long getVersionCodeForPackage(String packageName) throws RemoteException {
23586            try {
23587                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23588                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23589                if (pInfo != null) {
23590                    return pInfo.getLongVersionCode();
23591                }
23592            } catch (Exception e) {
23593            }
23594            return 0;
23595        }
23596    }
23597
23598    private class PackageManagerInternalImpl extends PackageManagerInternal {
23599        @Override
23600        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23601                int flagValues, int userId) {
23602            PackageManagerService.this.updatePermissionFlags(
23603                    permName, packageName, flagMask, flagValues, userId);
23604        }
23605
23606        @Override
23607        public boolean isDataRestoreSafe(byte[] restoringFromSigHash, String packageName) {
23608            SigningDetails sd = getSigningDetails(packageName);
23609            if (sd == null) {
23610                return false;
23611            }
23612            return sd.hasSha256Certificate(restoringFromSigHash,
23613                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23614        }
23615
23616        @Override
23617        public boolean isDataRestoreSafe(Signature restoringFromSig, String packageName) {
23618            SigningDetails sd = getSigningDetails(packageName);
23619            if (sd == null) {
23620                return false;
23621            }
23622            return sd.hasCertificate(restoringFromSig,
23623                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23624        }
23625
23626        @Override
23627        public boolean hasSignatureCapability(int serverUid, int clientUid,
23628                @SigningDetails.CertCapabilities int capability) {
23629            SigningDetails serverSigningDetails = getSigningDetails(serverUid);
23630            SigningDetails clientSigningDetails = getSigningDetails(clientUid);
23631            return serverSigningDetails.checkCapability(clientSigningDetails, capability)
23632                    || clientSigningDetails.hasAncestorOrSelf(serverSigningDetails);
23633
23634        }
23635
23636        private SigningDetails getSigningDetails(@NonNull String packageName) {
23637            synchronized (mPackages) {
23638                PackageParser.Package p = mPackages.get(packageName);
23639                if (p == null) {
23640                    return null;
23641                }
23642                return p.mSigningDetails;
23643            }
23644        }
23645
23646        private SigningDetails getSigningDetails(int uid) {
23647            synchronized (mPackages) {
23648                final int appId = UserHandle.getAppId(uid);
23649                final Object obj = mSettings.getUserIdLPr(appId);
23650                if (obj != null) {
23651                    if (obj instanceof SharedUserSetting) {
23652                        return ((SharedUserSetting) obj).signatures.mSigningDetails;
23653                    } else if (obj instanceof PackageSetting) {
23654                        final PackageSetting ps = (PackageSetting) obj;
23655                        return ps.signatures.mSigningDetails;
23656                    }
23657                }
23658                return SigningDetails.UNKNOWN;
23659            }
23660        }
23661
23662        @Override
23663        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23664            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23665        }
23666
23667        @Override
23668        public boolean isInstantApp(String packageName, int userId) {
23669            return PackageManagerService.this.isInstantApp(packageName, userId);
23670        }
23671
23672        @Override
23673        public String getInstantAppPackageName(int uid) {
23674            return PackageManagerService.this.getInstantAppPackageName(uid);
23675        }
23676
23677        @Override
23678        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23679            synchronized (mPackages) {
23680                return PackageManagerService.this.filterAppAccessLPr(
23681                        (PackageSetting) pkg.mExtras, callingUid, userId);
23682            }
23683        }
23684
23685        @Override
23686        public PackageParser.Package getPackage(String packageName) {
23687            synchronized (mPackages) {
23688                packageName = resolveInternalPackageNameLPr(
23689                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23690                return mPackages.get(packageName);
23691            }
23692        }
23693
23694        @Override
23695        public PackageList getPackageList(PackageListObserver observer) {
23696            synchronized (mPackages) {
23697                final int N = mPackages.size();
23698                final ArrayList<String> list = new ArrayList<>(N);
23699                for (int i = 0; i < N; i++) {
23700                    list.add(mPackages.keyAt(i));
23701                }
23702                final PackageList packageList = new PackageList(list, observer);
23703                if (observer != null) {
23704                    mPackageListObservers.add(packageList);
23705                }
23706                return packageList;
23707            }
23708        }
23709
23710        @Override
23711        public void removePackageListObserver(PackageListObserver observer) {
23712            synchronized (mPackages) {
23713                mPackageListObservers.remove(observer);
23714            }
23715        }
23716
23717        @Override
23718        public PackageParser.Package getDisabledPackage(String packageName) {
23719            synchronized (mPackages) {
23720                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23721                return (ps != null) ? ps.pkg : null;
23722            }
23723        }
23724
23725        @Override
23726        public String getKnownPackageName(int knownPackage, int userId) {
23727            switch(knownPackage) {
23728                case PackageManagerInternal.PACKAGE_BROWSER:
23729                    return getDefaultBrowserPackageName(userId);
23730                case PackageManagerInternal.PACKAGE_INSTALLER:
23731                    return mRequiredInstallerPackage;
23732                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23733                    return mSetupWizardPackage;
23734                case PackageManagerInternal.PACKAGE_SYSTEM:
23735                    return "android";
23736                case PackageManagerInternal.PACKAGE_VERIFIER:
23737                    return mRequiredVerifierPackage;
23738                case PackageManagerInternal.PACKAGE_SYSTEM_TEXT_CLASSIFIER:
23739                    return mSystemTextClassifierPackage;
23740            }
23741            return null;
23742        }
23743
23744        @Override
23745        public boolean isResolveActivityComponent(ComponentInfo component) {
23746            return mResolveActivity.packageName.equals(component.packageName)
23747                    && mResolveActivity.name.equals(component.name);
23748        }
23749
23750        @Override
23751        public void setLocationPackagesProvider(PackagesProvider provider) {
23752            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23753        }
23754
23755        @Override
23756        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23757            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23758        }
23759
23760        @Override
23761        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23762            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23763        }
23764
23765        @Override
23766        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23767            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23768        }
23769
23770        @Override
23771        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23772            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23773        }
23774
23775        @Override
23776        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23777            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23778        }
23779
23780        @Override
23781        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23782            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23783        }
23784
23785        @Override
23786        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23787            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23788        }
23789
23790        @Override
23791        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23792            synchronized (mPackages) {
23793                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23794            }
23795            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23796        }
23797
23798        @Override
23799        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23800            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23801                    packageName, userId);
23802        }
23803
23804        @Override
23805        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23806            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23807                    packageName, userId);
23808        }
23809
23810        @Override
23811        public void setKeepUninstalledPackages(final List<String> packageList) {
23812            Preconditions.checkNotNull(packageList);
23813            List<String> removedFromList = null;
23814            synchronized (mPackages) {
23815                if (mKeepUninstalledPackages != null) {
23816                    final int packagesCount = mKeepUninstalledPackages.size();
23817                    for (int i = 0; i < packagesCount; i++) {
23818                        String oldPackage = mKeepUninstalledPackages.get(i);
23819                        if (packageList != null && packageList.contains(oldPackage)) {
23820                            continue;
23821                        }
23822                        if (removedFromList == null) {
23823                            removedFromList = new ArrayList<>();
23824                        }
23825                        removedFromList.add(oldPackage);
23826                    }
23827                }
23828                mKeepUninstalledPackages = new ArrayList<>(packageList);
23829                if (removedFromList != null) {
23830                    final int removedCount = removedFromList.size();
23831                    for (int i = 0; i < removedCount; i++) {
23832                        deletePackageIfUnusedLPr(removedFromList.get(i));
23833                    }
23834                }
23835            }
23836        }
23837
23838        @Override
23839        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23840            synchronized (mPackages) {
23841                return mPermissionManager.isPermissionsReviewRequired(
23842                        mPackages.get(packageName), userId);
23843            }
23844        }
23845
23846        @Override
23847        public PackageInfo getPackageInfo(
23848                String packageName, int flags, int filterCallingUid, int userId) {
23849            return PackageManagerService.this
23850                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23851                            flags, filterCallingUid, userId);
23852        }
23853
23854        @Override
23855        public Bundle getSuspendedPackageLauncherExtras(String packageName, int userId) {
23856            synchronized (mPackages) {
23857                final PackageSetting ps = mSettings.mPackages.get(packageName);
23858                PersistableBundle launcherExtras = null;
23859                if (ps != null) {
23860                    launcherExtras = ps.readUserState(userId).suspendedLauncherExtras;
23861                }
23862                return (launcherExtras != null) ? new Bundle(launcherExtras.deepCopy()) : null;
23863            }
23864        }
23865
23866        @Override
23867        public boolean isPackageSuspended(String packageName, int userId) {
23868            synchronized (mPackages) {
23869                final PackageSetting ps = mSettings.mPackages.get(packageName);
23870                return (ps != null) ? ps.getSuspended(userId) : false;
23871            }
23872        }
23873
23874        @Override
23875        public String getSuspendingPackage(String suspendedPackage, int userId) {
23876            synchronized (mPackages) {
23877                final PackageSetting ps = mSettings.mPackages.get(suspendedPackage);
23878                return (ps != null) ? ps.readUserState(userId).suspendingPackage : null;
23879            }
23880        }
23881
23882        @Override
23883        public String getSuspendedDialogMessage(String suspendedPackage, int userId) {
23884            synchronized (mPackages) {
23885                final PackageSetting ps = mSettings.mPackages.get(suspendedPackage);
23886                return (ps != null) ? ps.readUserState(userId).dialogMessage : null;
23887            }
23888        }
23889
23890        @Override
23891        public int getPackageUid(String packageName, int flags, int userId) {
23892            return PackageManagerService.this
23893                    .getPackageUid(packageName, flags, userId);
23894        }
23895
23896        @Override
23897        public ApplicationInfo getApplicationInfo(
23898                String packageName, int flags, int filterCallingUid, int userId) {
23899            return PackageManagerService.this
23900                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23901        }
23902
23903        @Override
23904        public ActivityInfo getActivityInfo(
23905                ComponentName component, int flags, int filterCallingUid, int userId) {
23906            return PackageManagerService.this
23907                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23908        }
23909
23910        @Override
23911        public List<ResolveInfo> queryIntentActivities(
23912                Intent intent, int flags, int filterCallingUid, int userId) {
23913            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23914            return PackageManagerService.this
23915                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23916                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23917        }
23918
23919        @Override
23920        public List<ResolveInfo> queryIntentServices(
23921                Intent intent, int flags, int callingUid, int userId) {
23922            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23923            return PackageManagerService.this
23924                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23925                            false);
23926        }
23927
23928        @Override
23929        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23930                int userId) {
23931            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23932        }
23933
23934        @Override
23935        public ComponentName getDefaultHomeActivity(int userId) {
23936            return PackageManagerService.this.getDefaultHomeActivity(userId);
23937        }
23938
23939        @Override
23940        public void setDeviceAndProfileOwnerPackages(
23941                int deviceOwnerUserId, String deviceOwnerPackage,
23942                SparseArray<String> profileOwnerPackages) {
23943            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23944                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23945        }
23946
23947        @Override
23948        public boolean isPackageDataProtected(int userId, String packageName) {
23949            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23950        }
23951
23952        @Override
23953        public boolean isPackageStateProtected(String packageName, int userId) {
23954            return mProtectedPackages.isPackageStateProtected(userId, packageName);
23955        }
23956
23957        @Override
23958        public boolean isPackageEphemeral(int userId, String packageName) {
23959            synchronized (mPackages) {
23960                final PackageSetting ps = mSettings.mPackages.get(packageName);
23961                return ps != null ? ps.getInstantApp(userId) : false;
23962            }
23963        }
23964
23965        @Override
23966        public boolean wasPackageEverLaunched(String packageName, int userId) {
23967            synchronized (mPackages) {
23968                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23969            }
23970        }
23971
23972        @Override
23973        public void grantRuntimePermission(String packageName, String permName, int userId,
23974                boolean overridePolicy) {
23975            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23976                    permName, packageName, overridePolicy, getCallingUid(), userId,
23977                    mPermissionCallback);
23978        }
23979
23980        @Override
23981        public void revokeRuntimePermission(String packageName, String permName, int userId,
23982                boolean overridePolicy) {
23983            mPermissionManager.revokeRuntimePermission(
23984                    permName, packageName, overridePolicy, getCallingUid(), userId,
23985                    mPermissionCallback);
23986        }
23987
23988        @Override
23989        public String getNameForUid(int uid) {
23990            return PackageManagerService.this.getNameForUid(uid);
23991        }
23992
23993        @Override
23994        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23995                Intent origIntent, String resolvedType, String callingPackage,
23996                Bundle verificationBundle, int userId) {
23997            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23998                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23999                    userId);
24000        }
24001
24002        @Override
24003        public void grantEphemeralAccess(int userId, Intent intent,
24004                int targetAppId, int ephemeralAppId) {
24005            synchronized (mPackages) {
24006                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24007                        targetAppId, ephemeralAppId);
24008            }
24009        }
24010
24011        @Override
24012        public boolean isInstantAppInstallerComponent(ComponentName component) {
24013            synchronized (mPackages) {
24014                return mInstantAppInstallerActivity != null
24015                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24016            }
24017        }
24018
24019        @Override
24020        public void pruneInstantApps() {
24021            mInstantAppRegistry.pruneInstantApps();
24022        }
24023
24024        @Override
24025        public String getSetupWizardPackageName() {
24026            return mSetupWizardPackage;
24027        }
24028
24029        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24030            if (policy != null) {
24031                mExternalSourcesPolicy = policy;
24032            }
24033        }
24034
24035        @Override
24036        public boolean isPackagePersistent(String packageName) {
24037            synchronized (mPackages) {
24038                PackageParser.Package pkg = mPackages.get(packageName);
24039                return pkg != null
24040                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24041                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24042                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24043                        : false;
24044            }
24045        }
24046
24047        @Override
24048        public boolean isLegacySystemApp(Package pkg) {
24049            synchronized (mPackages) {
24050                final PackageSetting ps = (PackageSetting) pkg.mExtras;
24051                return mPromoteSystemApps
24052                        && ps.isSystem()
24053                        && mExistingSystemPackages.contains(ps.name);
24054            }
24055        }
24056
24057        @Override
24058        public List<PackageInfo> getOverlayPackages(int userId) {
24059            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24060            synchronized (mPackages) {
24061                for (PackageParser.Package p : mPackages.values()) {
24062                    if (p.mOverlayTarget != null) {
24063                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24064                        if (pkg != null) {
24065                            overlayPackages.add(pkg);
24066                        }
24067                    }
24068                }
24069            }
24070            return overlayPackages;
24071        }
24072
24073        @Override
24074        public List<String> getTargetPackageNames(int userId) {
24075            List<String> targetPackages = new ArrayList<>();
24076            synchronized (mPackages) {
24077                for (PackageParser.Package p : mPackages.values()) {
24078                    if (p.mOverlayTarget == null) {
24079                        targetPackages.add(p.packageName);
24080                    }
24081                }
24082            }
24083            return targetPackages;
24084        }
24085
24086        @Override
24087        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24088                @Nullable List<String> overlayPackageNames) {
24089            synchronized (mPackages) {
24090                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24091                    Slog.e(TAG, "failed to find package " + targetPackageName);
24092                    return false;
24093                }
24094                ArrayList<String> overlayPaths = null;
24095                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24096                    final int N = overlayPackageNames.size();
24097                    overlayPaths = new ArrayList<>(N);
24098                    for (int i = 0; i < N; i++) {
24099                        final String packageName = overlayPackageNames.get(i);
24100                        final PackageParser.Package pkg = mPackages.get(packageName);
24101                        if (pkg == null) {
24102                            Slog.e(TAG, "failed to find package " + packageName);
24103                            return false;
24104                        }
24105                        overlayPaths.add(pkg.baseCodePath);
24106                    }
24107                }
24108
24109                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24110                ps.setOverlayPaths(overlayPaths, userId);
24111                return true;
24112            }
24113        }
24114
24115        @Override
24116        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24117                int flags, int userId, boolean resolveForStart, int filterCallingUid) {
24118            return resolveIntentInternal(
24119                    intent, resolvedType, flags, userId, resolveForStart, filterCallingUid);
24120        }
24121
24122        @Override
24123        public ResolveInfo resolveService(Intent intent, String resolvedType,
24124                int flags, int userId, int callingUid) {
24125            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24126        }
24127
24128        @Override
24129        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
24130            return PackageManagerService.this.resolveContentProviderInternal(
24131                    name, flags, userId);
24132        }
24133
24134        @Override
24135        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24136            synchronized (mPackages) {
24137                mIsolatedOwners.put(isolatedUid, ownerUid);
24138            }
24139        }
24140
24141        @Override
24142        public void removeIsolatedUid(int isolatedUid) {
24143            synchronized (mPackages) {
24144                mIsolatedOwners.delete(isolatedUid);
24145            }
24146        }
24147
24148        @Override
24149        public int getUidTargetSdkVersion(int uid) {
24150            synchronized (mPackages) {
24151                return getUidTargetSdkVersionLockedLPr(uid);
24152            }
24153        }
24154
24155        @Override
24156        public int getPackageTargetSdkVersion(String packageName) {
24157            synchronized (mPackages) {
24158                return getPackageTargetSdkVersionLockedLPr(packageName);
24159            }
24160        }
24161
24162        @Override
24163        public boolean canAccessInstantApps(int callingUid, int userId) {
24164            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24165        }
24166
24167        @Override
24168        public boolean canAccessComponent(int callingUid, ComponentName component, int userId) {
24169            synchronized (mPackages) {
24170                final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
24171                return !PackageManagerService.this.filterAppAccessLPr(
24172                        ps, callingUid, component, TYPE_UNKNOWN, userId);
24173            }
24174        }
24175
24176        @Override
24177        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
24178            synchronized (mPackages) {
24179                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
24180            }
24181        }
24182
24183        @Override
24184        public void notifyPackageUse(String packageName, int reason) {
24185            synchronized (mPackages) {
24186                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
24187            }
24188        }
24189    }
24190
24191    @Override
24192    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24193        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24194        synchronized (mPackages) {
24195            final long identity = Binder.clearCallingIdentity();
24196            try {
24197                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
24198                        packageNames, userId);
24199            } finally {
24200                Binder.restoreCallingIdentity(identity);
24201            }
24202        }
24203    }
24204
24205    @Override
24206    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24207        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24208        synchronized (mPackages) {
24209            final long identity = Binder.clearCallingIdentity();
24210            try {
24211                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
24212                        packageNames, userId);
24213            } finally {
24214                Binder.restoreCallingIdentity(identity);
24215            }
24216        }
24217    }
24218
24219    @Override
24220    public void grantDefaultPermissionsToEnabledTelephonyDataServices(
24221            String[] packageNames, int userId) {
24222        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledTelephonyDataServices");
24223        synchronized (mPackages) {
24224            Binder.withCleanCallingIdentity( () -> {
24225                mDefaultPermissionPolicy.
24226                        grantDefaultPermissionsToEnabledTelephonyDataServices(
24227                                packageNames, userId);
24228            });
24229        }
24230    }
24231
24232    @Override
24233    public void revokeDefaultPermissionsFromDisabledTelephonyDataServices(
24234            String[] packageNames, int userId) {
24235        enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromDisabledTelephonyDataServices");
24236        synchronized (mPackages) {
24237            Binder.withCleanCallingIdentity( () -> {
24238                mDefaultPermissionPolicy.
24239                        revokeDefaultPermissionsFromDisabledTelephonyDataServices(
24240                                packageNames, userId);
24241            });
24242        }
24243    }
24244
24245    @Override
24246    public void grantDefaultPermissionsToActiveLuiApp(String packageName, int userId) {
24247        enforceSystemOrPhoneCaller("grantDefaultPermissionsToActiveLuiApp");
24248        synchronized (mPackages) {
24249            final long identity = Binder.clearCallingIdentity();
24250            try {
24251                mDefaultPermissionPolicy.grantDefaultPermissionsToActiveLuiApp(
24252                        packageName, userId);
24253            } finally {
24254                Binder.restoreCallingIdentity(identity);
24255            }
24256        }
24257    }
24258
24259    @Override
24260    public void revokeDefaultPermissionsFromLuiApps(String[] packageNames, int userId) {
24261        enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromLuiApps");
24262        synchronized (mPackages) {
24263            final long identity = Binder.clearCallingIdentity();
24264            try {
24265                mDefaultPermissionPolicy.revokeDefaultPermissionsFromLuiApps(packageNames, userId);
24266            } finally {
24267                Binder.restoreCallingIdentity(identity);
24268            }
24269        }
24270    }
24271
24272    private static void enforceSystemOrPhoneCaller(String tag) {
24273        int callingUid = Binder.getCallingUid();
24274        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24275            throw new SecurityException(
24276                    "Cannot call " + tag + " from UID " + callingUid);
24277        }
24278    }
24279
24280    boolean isHistoricalPackageUsageAvailable() {
24281        return mPackageUsage.isHistoricalPackageUsageAvailable();
24282    }
24283
24284    /**
24285     * Return a <b>copy</b> of the collection of packages known to the package manager.
24286     * @return A copy of the values of mPackages.
24287     */
24288    Collection<PackageParser.Package> getPackages() {
24289        synchronized (mPackages) {
24290            return new ArrayList<>(mPackages.values());
24291        }
24292    }
24293
24294    /**
24295     * Logs process start information (including base APK hash) to the security log.
24296     * @hide
24297     */
24298    @Override
24299    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24300            String apkFile, int pid) {
24301        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24302            return;
24303        }
24304        if (!SecurityLog.isLoggingEnabled()) {
24305            return;
24306        }
24307        Bundle data = new Bundle();
24308        data.putLong("startTimestamp", System.currentTimeMillis());
24309        data.putString("processName", processName);
24310        data.putInt("uid", uid);
24311        data.putString("seinfo", seinfo);
24312        data.putString("apkFile", apkFile);
24313        data.putInt("pid", pid);
24314        Message msg = mProcessLoggingHandler.obtainMessage(
24315                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24316        msg.setData(data);
24317        mProcessLoggingHandler.sendMessage(msg);
24318    }
24319
24320    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24321        return mCompilerStats.getPackageStats(pkgName);
24322    }
24323
24324    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24325        return getOrCreateCompilerPackageStats(pkg.packageName);
24326    }
24327
24328    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24329        return mCompilerStats.getOrCreatePackageStats(pkgName);
24330    }
24331
24332    public void deleteCompilerPackageStats(String pkgName) {
24333        mCompilerStats.deletePackageStats(pkgName);
24334    }
24335
24336    @Override
24337    public int getInstallReason(String packageName, int userId) {
24338        final int callingUid = Binder.getCallingUid();
24339        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24340                true /* requireFullPermission */, false /* checkShell */,
24341                "get install reason");
24342        synchronized (mPackages) {
24343            final PackageSetting ps = mSettings.mPackages.get(packageName);
24344            if (filterAppAccessLPr(ps, callingUid, userId)) {
24345                return PackageManager.INSTALL_REASON_UNKNOWN;
24346            }
24347            if (ps != null) {
24348                return ps.getInstallReason(userId);
24349            }
24350        }
24351        return PackageManager.INSTALL_REASON_UNKNOWN;
24352    }
24353
24354    @Override
24355    public boolean canRequestPackageInstalls(String packageName, int userId) {
24356        return canRequestPackageInstallsInternal(packageName, 0, userId,
24357                true /* throwIfPermNotDeclared*/);
24358    }
24359
24360    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24361            boolean throwIfPermNotDeclared) {
24362        int callingUid = Binder.getCallingUid();
24363        int uid = getPackageUid(packageName, 0, userId);
24364        if (callingUid != uid && callingUid != Process.ROOT_UID
24365                && callingUid != Process.SYSTEM_UID) {
24366            throw new SecurityException(
24367                    "Caller uid " + callingUid + " does not own package " + packageName);
24368        }
24369        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24370        if (info == null) {
24371            return false;
24372        }
24373        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24374            return false;
24375        }
24376        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24377        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24378        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24379            if (throwIfPermNotDeclared) {
24380                throw new SecurityException("Need to declare " + appOpPermission
24381                        + " to call this api");
24382            } else {
24383                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24384                return false;
24385            }
24386        }
24387        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24388            return false;
24389        }
24390        if (mExternalSourcesPolicy != null) {
24391            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24392            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24393                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24394            }
24395        }
24396        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24397    }
24398
24399    @Override
24400    public ComponentName getInstantAppResolverSettingsComponent() {
24401        return mInstantAppResolverSettingsComponent;
24402    }
24403
24404    @Override
24405    public ComponentName getInstantAppInstallerComponent() {
24406        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24407            return null;
24408        }
24409        return mInstantAppInstallerActivity == null
24410                ? null : mInstantAppInstallerActivity.getComponentName();
24411    }
24412
24413    @Override
24414    public String getInstantAppAndroidId(String packageName, int userId) {
24415        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24416                "getInstantAppAndroidId");
24417        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
24418                true /* requireFullPermission */, false /* checkShell */,
24419                "getInstantAppAndroidId");
24420        // Make sure the target is an Instant App.
24421        if (!isInstantApp(packageName, userId)) {
24422            return null;
24423        }
24424        synchronized (mPackages) {
24425            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24426        }
24427    }
24428
24429    boolean canHaveOatDir(String packageName) {
24430        synchronized (mPackages) {
24431            PackageParser.Package p = mPackages.get(packageName);
24432            if (p == null) {
24433                return false;
24434            }
24435            return p.canHaveOatDir();
24436        }
24437    }
24438
24439    private String getOatDir(PackageParser.Package pkg) {
24440        if (!pkg.canHaveOatDir()) {
24441            return null;
24442        }
24443        File codePath = new File(pkg.codePath);
24444        if (codePath.isDirectory()) {
24445            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
24446        }
24447        return null;
24448    }
24449
24450    void deleteOatArtifactsOfPackage(String packageName) {
24451        final String[] instructionSets;
24452        final List<String> codePaths;
24453        final String oatDir;
24454        final PackageParser.Package pkg;
24455        synchronized (mPackages) {
24456            pkg = mPackages.get(packageName);
24457        }
24458        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24459        codePaths = pkg.getAllCodePaths();
24460        oatDir = getOatDir(pkg);
24461
24462        for (String codePath : codePaths) {
24463            for (String isa : instructionSets) {
24464                try {
24465                    mInstaller.deleteOdex(codePath, isa, oatDir);
24466                } catch (InstallerException e) {
24467                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24468                }
24469            }
24470        }
24471    }
24472
24473    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24474        Set<String> unusedPackages = new HashSet<>();
24475        long currentTimeInMillis = System.currentTimeMillis();
24476        synchronized (mPackages) {
24477            for (PackageParser.Package pkg : mPackages.values()) {
24478                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24479                if (ps == null) {
24480                    continue;
24481                }
24482                PackageDexUsage.PackageUseInfo packageUseInfo =
24483                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24484                if (PackageManagerServiceUtils
24485                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24486                                downgradeTimeThresholdMillis, packageUseInfo,
24487                                pkg.getLatestPackageUseTimeInMills(),
24488                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24489                    unusedPackages.add(pkg.packageName);
24490                }
24491            }
24492        }
24493        return unusedPackages;
24494    }
24495
24496    @Override
24497    public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
24498            int userId) {
24499        final int callingUid = Binder.getCallingUid();
24500        final int callingAppId = UserHandle.getAppId(callingUid);
24501
24502        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24503                true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
24504
24505        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24506                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24507            throw new SecurityException("Caller must have the "
24508                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24509        }
24510
24511        synchronized(mPackages) {
24512            mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
24513            scheduleWritePackageRestrictionsLocked(userId);
24514        }
24515    }
24516
24517    @Nullable
24518    @Override
24519    public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
24520        final int callingUid = Binder.getCallingUid();
24521        final int callingAppId = UserHandle.getAppId(callingUid);
24522
24523        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24524                true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
24525
24526        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24527                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24528            throw new SecurityException("Caller must have the "
24529                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24530        }
24531
24532        synchronized(mPackages) {
24533            return mSettings.getHarmfulAppWarningLPr(packageName, userId);
24534        }
24535    }
24536
24537    @Override
24538    public boolean isPackageStateProtected(@NonNull String packageName, @UserIdInt int userId) {
24539        final int callingUid = Binder.getCallingUid();
24540        final int callingAppId = UserHandle.getAppId(callingUid);
24541
24542        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24543                false /*requireFullPermission*/, true /*checkShell*/, "isPackageStateProtected");
24544
24545        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID
24546                && checkUidPermission(MANAGE_DEVICE_ADMINS, callingUid) != PERMISSION_GRANTED) {
24547            throw new SecurityException("Caller must have the "
24548                    + MANAGE_DEVICE_ADMINS + " permission.");
24549        }
24550
24551        return mProtectedPackages.isPackageStateProtected(userId, packageName);
24552    }
24553}
24554
24555interface PackageSender {
24556    /**
24557     * @param userIds User IDs where the action occurred on a full application
24558     * @param instantUserIds User IDs where the action occurred on an instant application
24559     */
24560    void sendPackageBroadcast(final String action, final String pkg,
24561        final Bundle extras, final int flags, final String targetPkg,
24562        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
24563    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24564        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
24565    void notifyPackageAdded(String packageName);
24566    void notifyPackageRemoved(String packageName);
24567}
24568